You are here: Home / Topics / Program to Visibility Control in Same Package example in Java

Program to Visibility Control in Same Package example in Java

Filed under: Java on 2023-09-17 15:37:29

// Program to Visibility Control in Same Package.

// First File ( Base.java ) in package p1
package p1;

public class Base 
{
private int n_pri = 1;
int n_def = 2;
protected int n_pro = 3;
public int n_pub = 4;

public Base() 
{
 System.out.println("base constructor");
 System.out.println("n_pri = " + n_pri);
 System.out.println("n_def = " + n_def);
 System.out.println("n_pro = " + n_pro);
 System.out.println("n_pub = " + n_pub);
}
}

// Second File ( Derived.java ) in package p1 : 
package  p1;

class  Derived  extends  Base 
{
Derived() 
{
 System.out.println("derived constructor");
 // class only
 // System.out.println("n_pri = "4 + n_pri);
 System.out.println("n_def = " + n_def);
 System.out.println("n_pro = " + n_pro);
 System.out.println("n_pub = " + n_pub);
}
}

// Third File ( SamePackage.java ) in package p1 
package  p1;

class  SamePackage 
{
SamePackage() 
{
 Base b = new Base();
 System.out.println("same package constructor");
 // class only
 // System.out.println("n_pri = " + b.n_pri);
 System.out.println("n_def = " + b.n_def);
 System.out.println("n_pro = " + b.n_pro);
 System.out.println("n_pub = " + bl.n_pub);
}
}

// Fourth File ( Demo.java ) in package p1
package  p1;

// Instantiate the various classes in p1.
public class  Demo 
{
public static void main(String args[ ]) 
{
 Base ob1 = new Base();
 Derived ob2 = new Derived();
 SamePackage ob3 = new SamePackage();
}
}


Output:

base constructor
n_pri = 1
n_def = 2
n_pro = 3
n_pub = 4

base constructor
n_pri = 1
n_def = 2
n_pro = 3
n_pub = 4

derived constructor
n_def = 2
n_pro = 3
n_pub = 4

base constructor
n_pri = 1
n_def = 2
n_pro = 3
n_pub = 4

same package constructor
n_def = 2
n_pro = 3
n_pub = 4

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others. This portal helps students in getting study material free.