Notes on Inheritance

 

Inheritance allows you to make specialized sub-classes that can provide additional functionality or define separate types of the class.

Classes are defined in a tree structured hierarchical relationship.  Classes have parents or super classes and may have children or derived classes.  Consider the hierarchical relationships of animals or vehicles.

 

You can define a derived class by using the extends clause on the class statement:

 

     public class Vehicle {

          protected float weight;

     public Vehicle( float w) {

          weight = w;

     }

     public float tax() {

          return weight * 0.01;

     }

     }

 

     public class Car extends Vehicle {

          int seats;

     }

 

     public class Truck extends Vehicle {

          float payload;

     }

 

Derived classes have all of the functionality of the super class.  Derived classes can access the public and protected variables and methods of the super class.

 

     Car junker = new Car( 2000.0f );

     float fee = junker.tax();

 

Polymorphism is the ability to define actions for the parent class and then apply them to different derived classes.

 

     Vehicle x, y;

     x = new Car();

     y = new Truck();

 


Constructors of derived classes can call the constructor or the super class by calling the “super” method.  The keyword super refers to the super or parent class.  A possible constructor for Car might be:

 

     public Car (float heavy, int holds) {

          super(heavy);      // call constructor of Vehicle

          seats = holds;

     }

 

One instance of an object can reference the public, private and protected variables and methods of another instance of its own class.

 

Abstract classes exist for the sole purpose of being extended.  Abstract classes can have abstract methods.  An abstract method has the interface defined, but does not define the body of the method.  The method must be defined in a derived class.

 

     abstract public class Vehicle {

          protected float weight;

     public Vehicle( float w) {

          weight = w;

     }

     public float tax() {

          return weight * 0.01;

     }

     abstract public float capacity();

     }

 

     public class Car extends Vehicle {

          int seats;

     public Car (float heavy, int holds) {

          super(heavy);      // call constructor of Vehicle

          seats = holds;

     }

     public float capacity() {

          return (float)seats;

     }

     }

 

     public class Truck extends Vehicle {

          float payload;

     public float capacity() {

          return payload;

     }

}