Alex Rivera | Logout

What is the difference between public, protected, package-private and private in Java?

Asked 2008-10-18T19:53:12.187
3737

In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?

Edit
Report

1 Answer

12

This page writes well about the protected & default access modifier

.... Protected: Protected access modifier is the a little tricky and you can say is a superset of the default access modifier. Protected members are same as the default members as far as the access in the same package is concerned. The difference is that, the protected members are also accessible to the subclasses of the class in which the member is declared which are outside the package in which the parent class is present.

But these protected members are “accessible outside the package only through inheritance“. i.e you can access a protected member of a class in its subclass present in some other package directly as if the member is present in the subclass itself. But that protected member will not be accessible in the subclass outside the package by using parent class’s reference. ....

answered 2012-03-15T11:53:50.620

Your Answer