Tuesday, February 27, 2007

Access Modifiers in Java

Difference between Default and Protected :

Default access modifier is package oriented. For example, Consider Class A has a method or member with default access modifier ,and Class B inherits Class A.Class B can only access the method or member of Class A, if and only if Class B is in the same package as class A.

In case of Protected , it is parent - child oriented. That is , for the above example, Class B can access the protected methods or members of Class A, eventhough Class B belongs to any other package.

In both cases , it is assumed that Class B inherits Class A, and class A is visbile to all classes,i.e, Class A is declared as Public.

And one more thing is, The subclass can see the protected member only through inheritance , and not by creating a instance of the superclass.

The protected member of class A can be accessed by the subclasses of Class B and not by other classes present in the Class B's package by instantiating Class B.

No comments: