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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more