Explore Courses Blog Tutorials Interview Questions
+1 vote
in Java by (830 points)

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?

1 Answer

0 votes
by (13.2k points)

In java there are 4 access modifiers private, public, protected and default ( when no access modifier is defined). They are mainly used to reduce the accessibility of the class, variables etc.

  1. Private

 private classes, variables etc are only accessible in its own class ( the one in which it is declared). It is also referred as the highest form of encapsulation that can be provided in Java. It is considered a good programming practise in java to declare variables private by default. A private member cannot be overwritten as well.

  1. Public

public is least restrictive access modifier and its not such a good thing to declare things by default public (specially in big code) because if made public it's very difficult to make changes in the internal structure of class as it affects the whole code (which might be used by other people too).

  1. Protected

The private and protected are very similar, except for the fact that in protected access specifier the variables, classes etc are not only available for use inside its own class but also outside on a subclass. Declaring a variable protected means it can be used if your class is extended.

  1. Package or default

 Package or the default access specifier comes next to private access specifier in terms of restrictiveness for any variable, class etc. If no access specifier is given to a class it is said to be having the default package modifier by default. When a variable, class is declared as package-private then it is only available on the package it belongs to.

Browse Categories