next up previous contents
Next: Polymorphism & Dynamic Binding Up: Java Notes Previous: Inheritance: Overriding

Inheritance 1: Basic Example


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

class Superclass{
  public void supermethod(){
    System.out.println("Superclass");
  }
}

//This class inherits supermethod from Superclass
//so that it can be called for subclass objects
class Subclass extends Superclass{
  public void submethod(){
    System.out.println("Subclass");
  }
}

class l1Inherit1{//Inherit1
  public static void main(String[] args){
    //Create a superclass object and call a
    //superclass method
    Superclass superclass = new Superclass();
    superclass.supermethod();

    //Create a subclass object and call both
    //a subclass and superclass method
    Subclass subclass = new Subclass();
    subclass.supermethod();
    subclass.submethod();

    //This assignment is valid, the reverse is not.
    superclass = subclass;
  }
}
/******** sample compilation & run ********
# javac l1Inherit1.java
# java l1Inherit1     
Superclass
Superclass
Subclass
# 
******************************************/



Ananda Amatya
9/15/1999