Java Basics  «Prev 

Restrict access to Instance Variables

Access Control for Inheritance using Java

Once you can access a class, what are the controls you can place on its members?
You can restrict access to instance variables and methods from one class to another. And it is not always the case that a subclass can access the methods and variables of its superclass. Sometimes you want to keep certain data or behavior hidden even from subclasses.

private keyword in Java

For example, a class called Vehicle, acting as a superclass for all Car, Bus, and Truck classes, might maintain the Vehicle's VIN (Vehicle Identification Number) and want to keep it private.
The Vehicle class can use a keyword to accomplish this, called naturally enough private.
class Vehicle {
  private char[] vin = new char[25]; 
}

The only way to access this vin variable outside of the Vehicle class is for the Vehicle class to provide a method that accesses it.
For example, the Vehicle class might provide a method that checks its private VIN with one passed into a method:

class Vehicle {
  private char[] vin = new char[25];
  booleancompareVIN(char[] comparisonVIN) {
  for(int i = 0; i < 25; i++){
    if (vin[i] != comparisonVIN[i]){
     returnfalse; 
    }
    returntrue; 
  }// end -for}

Since there is no way for any other class to access this variable, we also need a way for the Vehicle class to initialize it.
We might accomplish this by defining a constructor that takes a char array as an argument and initializes vin appropriately.
If we made a subclass, perhaps like this:

classCar extends Vehicle { 
  // code goes here
}

there is no way we could include a method for Car that would access the private variable named vin in the Vehicle class.

protected

We can also declare a member (a variable or method) to be protected.
A protected variable or method is available only to that class and its subclasses (or to classes defined in the same package as the class defining the protected member). Classes in other packages that are not subclasses cannot access protected members.
With the example just given, if we had used protected instead of private, as in:

protected char[] vin = new char[25]; 

then Car could have accessed vin directly. However, other classes in other packages would not be able to access vin.

public

At the other extreme, if we declared vin using the keyword public, any class could access vin, in this or any other package.

The default Access

The default, without any keywords, makes a member accessible only within the package that defines it.