Tutorials : The Pitfalls of Inheritance :

Modifying the Super Class Behavior…

With inheritance mechanism, although the sub class by default inherits all the interfaces and implementations of the super class, it is possible to override any of the implementations in the sub class. It is also perfectly possible to extend the interfaces by adding new methods to the sub class. Both of these are mechanisms to modify or extend the functionality of the super class. For example, consider the following inheritance scenario in Listing 1.
public class Vehicle

{

   public void stop()

   {

       //stop the engine

 

   }

 

public void accelarate()

   {

       

   }

}

 

 

public class Car extends Vehicle

{

 

    public Car()

    {

 

    }

 

    public void stop()

    {

        //stop the engine

        //lock the steering wheel

    }

 

  public void switchOnWiper()

    {

        

    }

 

}
Listing 1: The Vehicle-Car interface inheritance

In this example, we have modelled Car IS A Vehicle. The Car class overrides the stop() method implementation of its super class Vehicle. However, it decides to reuse the accelarate() implementation from its super class.

As a result of this inheritance relationship, we will be able to write a VehicleTester class in the following form.

public class VehicleTester

{

    

    public void testVehicle(Vehicle vechicle)

    {

        //test the accelarate behaviour

        vechicle.accelarate();

        //test the stop behaviour

        vechicle.stop();

    }

 

}
Listing 2. The example benefits of using inheritance relationship

In this example, you can immediately see the benefits of inheritance relationship. We could write a single method accepting a super class type and we are able to pass any sub class to the same method. This greatly reduces the strongly typed nature of code and increases the flexibility of the application module.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.