Access Control Example included from the book 'Java - The Complete Reference' Eighth Edition, demonstrates the various levels of access.
// File : p1\Protection.java
package p1;
class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
// File : p1\Derived.java
package p1;
class Derived extends Protection
{
public Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
// System.out.println("n_pri = " + n_pri); // WILL NOT WORK
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
// File : p1\SamePackage.java
package p1;
class SamePackage
{
public SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// System.out.println("n_pri = " + p.n_pri); // WILL NOT WORK
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
// File : p2\Protection2.java
package p2;
class Protection2 extends p1.Protection
{
public Protection2()
{
System.out.println("derived other package constructor");
// System.out.println("n = " + n); // WILL NOT WORK
// System.out.println("n_pri = " + n_pri); // WILL NOT WORK
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
// File : p2\OtherPackage.java
package p2;
class OtherPackage
{
public OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// System.out.println("n = " + n); // WILL NOT WORK
// System.out.println("n_pri = " + n_pri); // WILL NOT WORK
// System.out.println("n_pro = " + n_pro); // WILL NOT WORK
System.out.println("n_pub = " + n_pub);
}
}
If you want try this program, first create the files
Protection.java
,
Derived.java
and
SamePackage.java
in the directory
p1
and
Protection2.java
and
OtherPackage.java
in the directory
p2
. Then copy the respective code into those java files.
Create the following
Demo.java
file to test the classes in package
p1
.
// File : p1\Demo.java
package p1;
class Demo
{
public static void main(String s[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
Create the following
Demo.java
file to test the classes in package
p2
.
// File : p2\Demo.java
package p2;
class Demo
{
public static void main(String s[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}