Understanding Packages and Access Modifiers in Java: Example 1

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

Table of Content:

Within class

We are trying to access a private method Within Same Package and same class.

private method Within Same Package and same class

Program

package pack1;

class ClassB{

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

public static void main(String args[])
  {
    System.out.println("This is ClassB");

    ClassB object = new ClassB();
    object.MethodOfClassA();
  }
} 

Output

 
C:\Users\Hello World>E:

E:\>cd  

E:\>javac -d . ClassB.java

E:\>java pack1.ClassB
This is ClassB
Method of ClassA

E:\>

Within same package two different class

private method Within Same Package and same class

Program

Sava file as: ClassA.java
package pack1;
Class A{

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

 void duMethodOfClassA{
   System.out.println("Default Method of ClassA");
 
 }

 public void puMethodOfClassA{
   System.out.println("public Method of ClassA");
 
 }

} 
Sava file as: ClassB.java
package pack1;
import pack1.ClassA;

class ClassB{

  public static void main(String args[])
  {
 	ClassA object = new ClassA();
 	System.out.println(object.x);
 	System.out.println(object.y);
   // System.out.println(object.z); // not possible


    object.dMethodOfClassA();
    object.puMethodOfClassA();
   // object.prMethodOfClassA(); // not possible
 
  }

} 

Output

  

C:\Users\Hello World>E: 

E:\>javac -d . ClassA.java

E:\>javac -d . ClassB.java

E:\>java pack1.ClassB
10
12
Default Method of ClassA
public Method of ClassA

E:\>

Short Overview

Short Overview of package

A Non public class has package-access.

non public class has package-access

Short Overview for Sub Class

Short Overview for Sub Class