The Java Program: ProtectedMain.java

  1 class Base {
  2 
  3    private   int x=1;
  4    protected int y=2;
  5    public    int z=3;
  6 
  7    public int getX () { return x; }
  8    public int getY () { return y; }
  9    public int getZ () { return z; }
 10 
 11 }
 12 
 13 class Derived extends Base {
 14 
 15    /*
 16      The private member field "x" of "Base" is inherited,
 17      but access to it from a derived class is not allowed.
 18    */
 19 
 20    public int getXX () { return getX(); }
 21 
 22    /*
 23      The protected member field "y" of "Base" is inherited,
 24      and access to it from a derived class is allowed, but
 25      not from classes that don't extend "Base".
 26    */
 27 
 28    public int y2 = y;
 29 
 30    public int getYY () { return y; }
 31 }
 32 
 33 public class ProtectedMain {
 34    public static void main (String[] args) {
 35       final Derived d = new Derived ();
 36 
 37       // "d.x" is not allowed.
 38 
 39       System.out.println (d.getX());
 40       System.out.println (d.getXX());
 41 
 42       // "d.y" is not allowed.
 43 
 44       System.out.println (d.getY());
 45       System.out.println (d.getYY());
 46 
 47 
 48    }
 49 
 50 
 51 }