next up previous contents
Next: Interface Up: Java Notes Previous: Inheritance 11: super 1

Inheritance 12: super 2


/**
 *  This code is from the book:
 *  Winder, R and Roberts, G (1998)
 *  Developing Java Software</em>
 *  John Wiley & Sons.
 *  It is copyright (c) 1997 Russel Winder
 *  and Graham Roberts.
 */

class Superclass{
  public int i = 5;
  protected int j = 10;
  private int k = 20;

  public void show(){
    System.out.println("Superclass " + i + 
                       " " + j + " " + k);
  }
}

class Subclass extends Superclass{

  // Instance variable that hide
  // those inherited from Superclass
  public int i = 1;
  protected int j = 2;
  private int k = 3;

  public void test(){
    // Display initial values of instance variables
    show();
    //Call superclass show method using super
    super.show();

    //Access superclass variables that 
    //have been hidden
    super.i = 100;
    super.j = 200;
    //Can't access a private variable
    //super.k = 30; //Error

    //Access this classes instance variables normally
    i = 1000;
    j = 2000;
    k = 3000;//No problem accessing private variable
             //belonging to this class

    //Show values of instance variables again
    show();
    super.show();
  }

  //Overridden method
  public void show(){
    System.out.println("Subclass " + i + 
                       " " + j + " " + k);
  }
}

class l1Inherit12{//Super2
  public static void main(String[] args){
    Subclass subclass = new Subclass();
    subclass.test();
  }
}
/******** sample compilation & run *******
# javac l1Inherit12.java 
# java l1Inherit12
Subclass 1 2 3
Superclass 5 10 20
Subclass 1000 2000 3000
Superclass 100 200 20
# 
******************************************/



Ananda Amatya
9/15/1999