next up previous contents
Next: Inheritance 8: Abstract Method Up: Java Notes Previous: Inheritance 6: Method Lookup

Inheritance 7: Abstract Class


/**
 *  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.
 */

abstract class Superclass{
  protected int i = 10;
  protected int j = 20;

  //Shared method not to be overridden
  public final void f(){
    System.out.println("Superclass:test");
  }

  //Method intended to be overridden but
  //including a default implementation.
  public void common(){
    System.out.println("Superclass:common");
  }
}

class Subclass extends Superclass{
  public void test(){
    //Can call superclass method
    f();
    //Can use superclass instance variables
    i = 20;
  }
}

class Subclass2 extends Superclass{
  public void common(){
    System.out.println("Subrclass2:test");
  }
}

class l1Inherit7{//Abstract1
  public static void main(String[] args){
    //Can't create Superclass objects
    //Superclass superclass = new Superclass();

    Subclass subclass = new Subclass();
    subclass.test();

    //Can do this assignment and call method in
    //shared public interface
    Superclass superclass = subclass;
    superclass.common();
    //Can also create Subclass2 object and call common
    superclass = new Subclass2();
    superclass.common();

    //Method f is also part of shared interface
    subclass.f();
    superclass.f();
  }
}
/******** sample compilation & run *******
# javac l1Inherit7.java 
# java l1Inherit7
Superclass:test
Superclass:common
Subrclass2:test
Superclass:test
Superclass:test
# 
******************************************/



Ananda Amatya
9/15/1999