Question

What is the difference between public, private, and protected keywords? Do I even need to use them?

Answer

We use these keywords to specify access levels for member variables, or for member functions (methods).

Deciding when to use private, protected, or public variables is sometimes tricky. You need to think whether or not an external object (or program), actually needs direct access to the information. If you do want other objects to access internal data, but wish to control it, you would make it either private or protected, but provide functions which can manipulate the data in a controlled way.

Take the following example :

public class bank_balance
{
	public String owner;
	public int balance; 

	public bank_balance( String name, int dollars )
	{
		owner = name;

		if (dollars >= 0)
			balance = dollars;
		else
			dollars =0;
	}
}

We have declared our string and integer to be public. This means that any object in the system can change the balance (setting it to zero, or even giving us a negative balance). This could cause the program to fall over, even though we wrote code in our constructor to prevent negative balances.

Instead, we should have provided a getBalance/setBalance method, and made our balance private or proteced. Other objects can still access the data, but they can't put invalid data in.

public class bank_balance
{
	public String owner;
	private int balance; 

	public bank_balance( String name, int dollars )
	{
		owner = name;

		if (dollars >= 0)
			balance = dollars;
		else
			dollars =0;
	}

	public int getBalance()
	{
		return balance;
	}

	public void setBalance(int dollars)
	{
		if (dollars >= 0)
			balance = dollars;
		else
			dollars = 0;		
	}
}


Back