Monday, November 10, 2008

Member Access and Inheritance

Member Access and Inheritance:

 

Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private.

 

For example, consider the following simple class hierarchy:

 

/* In a class hierarchy, private members remain private to their class.

This program contains an error and will not compile.

*/

// Create a superclass.

class A {

int i; // public by default

private int j; // private to A

void setij(int x, int y) {

i = x;

j = y;

}

}

// A's j is not accessible here.

class B extends A {

int total;

void sum() {

total = i + j; // ERROR, j is not accessible here

}

}

class Access {

public static void main(String args[]) {

B subOb = new B();

subOb.setij(10, 12);

subOb.sum();

System.out.println("Total is " + subOb.total);

}

}

 

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

 

A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses.

No comments: