Member Access and Inheritance


Thus a subclass can access all the data members and methods from the superclass that has been extended. But the data members and methods of the superclass that have been declared "private" will not be able to access the data members and methods. The following example shows this:

Program
//In a class hierarchy, private members remin private to their class.

//This program contains an error and will not compile.

//Create a superclass
class X
{
 int _a; // public by default
 private int _b; // private to X
 
 void Setab(int a, int b)
 {
  this._a=a;
  this._b=b;
 }
}

// X's _b is not accessible here.
class Y extends X
{
 int _total;
 int Sum()
 {
  _total=_a+_b; // Error, _b is not accessible here
  return _total;
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
    Y subobj=new Y();
    subobj.Setab(10,20);
    System.out.println("Sum of _a + _b : "+subobj.Sum());
  }
}

This program will not compile because the use of "_b" inside the "Sum()" method of "Y" causes an access violation. Since "_b" is declared as "private", it is only accessible by other members of its own class. Subclasses have no access to it.

Note : The member of the class that has been declared private will remain private in his class. It is not accessible by any code outside of its class including subclass.