Exploring Packages and Access Modifiers in Java: Example 2
☰Fullscreen
Table of Content:
Within Same Package (default method)
We are trying to access a default method within same package but from the different class
Save file: ClassA.javapackage pack1; class ClassA{ void MethodOfClassA() { System.out.println("Method of ClassA"); } public static void main(String args[]) { } }Save file: ClassB.java
package pack1; class ClassB{ public static void main(String args[]) { System.out.println("This is ClassB"); ClassA object = new ClassA(); object.MethodOfClassA(); } }
Output
C:\Users\Hello World>E: E:\> E:\>javac -d . ClassA.java E:\>javac -d . ClassB.java E:\>java pack1.ClassB This is ClassB Method of ClassA
Within Same Package (public method)
We are trying to access a public method Within Same Package but from the different class
Save file: ClassA.javapackage pack1; class ClassA{ public void MethodOfClassA() { System.out.println("Method of ClassA"); } public static void main(String args[]) { } }Save file: ClassB.java
package pack1; class ClassB{ public static void main(String args[]) { System.out.println("This is ClassB"); ClassA object = new ClassA(); object.MethodOfClassA(); } }
Output
E:\>javac -d . ClassA.java E:\>javac -d . ClassB.java E:\>java pack1.ClassB This is ClassB Method of ClassA
Within Same Package (protected method)
We are trying to access a protected method Within Same Package but from the different class
Save file: ClassA.javapackage pack1; class ClassA{ protected void MethodOfClassA() { System.out.println("Method of ClassA"); } public static void main(String args[]) { } }Save file: ClassB.java
package pack1; class ClassB{ public static void main(String args[]) { System.out.println("This is ClassB"); ClassA object = new ClassA(); object.MethodOfClassA(); } }
Output
E:\>javac -d . ClassA.java E:\>javac -d . ClassB.java E:\>java pack1.ClassB This is ClassB Method of ClassA
Within Same Package (private method)
We are trying to access a private method Within Same Package but from the different class
Save file: ClassA.javapackage pack1; class ClassA{ private void MethodOfClassA() { System.out.println("Method of ClassA"); } public static void main(String args[]) { } }Save file: ClassB.java
package pack1; class ClassB{ public static void main(String args[]) { System.out.println("This is ClassB"); ClassA object = new ClassA(); object.MethodOfClassA(); } }
Output
E:\>javac -d . ClassA.java E:\>javac -d . ClassB.java ClassB.java:9: error: MethodOfClassA() has private access in ClassA object.MethodOfClassA(); ^ 1 error