DEV Community

Cover image for Access modifier
     NSP.Mathi
NSP.Mathi

Posted on

Access modifier

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?
Image description

Ans:
private hides from other classes within the package.
public exposes to classes outside the package.
protected is a version of public restricted only to subclasses.

For example, if I have MyClass and I'm doing AnotherClass extends MyClass I will have access to all protected and public methods and properties from within AnotherClass. If I do MyClass myClass = new MyClass(); in AnotherClass somewhere - let's say the constructor - I will only have access to the public methods if it is in a different package. Note that if I do = new MyClass() { @Override protected void protectedMethod() { //some logic } }; it appears that I can access protected methods, but this kind of the same as extending it, but inline instead.

Top comments (0)