Java program for packages to understand visibility modifiers

 A.java


package p1;

public class A

{

int pack = 1;

private int pri = 2;

protected int pro = 3;

public int pub = 4;

public A()

{

System.out.println("Base Constructor");

System.out.println(pack);

System.out.println(pri);

System.out.println(pro);

System.out.println(pub);

}

}


Compile :- javac -d . A.java


B.java


package p1;

class B extends A

{

public B()

{

System.out.println("Derived Constructor");

System.out.println(pack);

//System.out.println(pri);

System.out.println(pro);

System.out.println(pub);

}

}

Compile :- javac -d . B.java

C.java


package p1;

public class C

{

public C()

{

A ob = new A();

System.out.println("Same Package Constructor");

System.out.println(ob.pack);

//System.out.println(ob.pri);

System.out.println(ob.pro);

System.out.println(ob.pub);

}

}

Compile :- javac -d . C.java

D.java


package p2;

class D extends p1.A

{

D()

{

System.out.println("D Constructor");

//System.out.println(pack);

//System.out.println(pri);

System.out.println(pro);

System.out.println(pub);

}

}

Compile :- javac -d . D.java

E.java


package p2;

import p1.*;

class E 

{

E()

{

A ob = new A();

System.out.println("E Constructor");

//System.out.println(ob.pack);

//System.out.println(ob.pri);

//System.out.println(ob.pro);

System.out.println(ob.pub);

}

}

Compile :- javac -d . E.java

Test1.java


package p1;

class Test1

{

public static void main(String ar[])

{

A ob1 = new A();

B ob2 = new B();

C ob3 = new C();

}

}

Compile :-   javac -d . Test1.java

Run :-   java p1.Test1


Test2.java


package p2;

class Test2

{

public static void main(String ar[])

{

D ob1 = new D();

E ob2 = new E();

}

}

Compile :-   javac -d . Test2.java

Run :-   java p2.Test2


OUTPUT






Comments