Mastering Packages and Access Modifiers in Java: Example 4

Rumman Ansari   Software Engineer   2024-07-05 03:36:19   6649  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Different Package different class (private method)

We are trying to access a private method Within different Package and different class

ClassA is not public in pack1; can be accessed from outside package

MethodOfClasB() has private access in ClassA. It should not be private, it should be public to run.

should be public

Different Package Different Class Save file: ClassA.java
package pack1;

public class ClassA{

	public int x = 10;
	int y = 12;
	private int z = 14;

  public void MethodOfClassA()
 	{
 	 System.out.println("Method of ClassA");
	}
	
     public void MethodOfClassB()
 	{
 	 System.out.println("Method of ClassB private");
	}	

}
Save file: ClassB.java
package pack2;
import pack1.ClassA;

class ClassB{

  public static void main(String args[])
  {
 	ClassA object = new ClassA();
 	System.out.println(object.x);
    object.MethodOfClassA();

  //  system.out.println(object.y); // not possible
  //  system.out.println(object.z); // not possible
  
  	
   //  object.MethodOfClassB(); // not possible
  }

}
 
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.

C:\Users\Hello World>E:
 
E:\>javac -d . ClassA.java

E:\>javac -d . ClassB.java

E:\>java pack2.ClassB
10
Method of ClassA

E:\>