Modifiers are applied to class, interface and its members. Java supports two types of modifiers-
You can apply public access modifier to classes, interfaces, and their members. It makes Java element most accessible or least restrictive which means that element can be accessed from all packages.
package package1; public class X { public void display() { System.out.println("I am in package1"); } }
package package2; import package1.*; class Y { public static void main(String args[]) { X x = new X(); x.display(); } }
Output
I am in package1
The members of a class defined with protected access modifiers are accessible in-
package package1; public class X { protected void display() { System.out.println("I am in package1"); } }
package package2; import package1.*; class Y { public static void main(String args[]) { X x = new X(); x.display(); } }
Output
Compile Time Error
Note- Members of an interface are implicitly public. If you declare interface members as protected, then they won't compile.
There is no keyword default for the default modifier. If an element does not explicitly use any modifier, the default access is implied. It may be applied to a class, a variable, or a method. It is only accessible within the package.
package package1; class X { void display() { System.out.println("I am in package1"); } }
package package2; import package1.*; class Y { public static void main(String args[]) { X x = new X(); x.display(); } }
Output
Compile Time Error
class X { private int info = 10; private void display() { System.out.println("I am in X class"); } } public class Y { public static void main(String args[]) { X x = new X(); System.out.println(x.info); x.display(); } }
Output
Compile Time Error
Access Modifiers | Same Package | Different Package | ||
---|---|---|---|---|
Derived Classes | Separate Classes | Derived Classes | Separate Classes | |
public | Allowed | Allowed | Allowed | Allowed |
protected | Allowed | Allowed | Allowed | Not Allowed |
default | Allowed | Allowed | Not Allowed | Not Allowed |
private | Not Allowed | Not Allowed | Not Allowed | Not Allowed |