Thursday, July 29, 2010

Inheritance in java

Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An example of where this could be useful is with an employee records system. You could create a generic employee class with states and actions that are common to all employees. Then more specific classes could be defined for salaried, commissioned and hourly employees. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.

The Object class is the highest superclass (ie. root class) of Java. All other classes are subclasses (children or descendants) inherited from the Object class. The Object class includes methods such as:
clone()equals()copy(Object src)finalize() getClass()
hashCode()notify() notifyAll()toString()wait()

Inheritance in Java
Java uses the extends keyword to set the relationship between a parent class and a child class. For example using our Box class from notes about class :

public class GraphicsBox extends Box
 
The GraphicsBox class assumes or inherits all the properties of the Box class and can now add its own properties and methods as well as override existing methods. Overriding means creating a new set of method statements for the same method signature (name, number of parameters and parameter types). For example:
// define position locations
    private int left, top;
// override a superclass method
    public int displayVolume()
    {
      System.out.println(length*width*height);
      System.out.println("Location: "+left+", "+top);
    }

When extending a class constructor you can reuse the superclass constructor and overridden superclass methods by using the reserved word super. Note that this reference must come first in the subclass constructor. The reserved word this is used to distinguish between the object's property and the passed in parameter.
   GraphicsBox(l,w,h,left,top)
    {
      super (l,w,h);
      this.left=left;
      this.top=top;
    }
    public void showObj()
    {    System.out.println(super.showObj()+"more stuff here");
     }

The reserved word this can also be used to reference private constructors which are useful in initializing properties.
Special Note:You cannot override final methods, methods in final classes, private methods or static methods.

See Further

Inheritance : cpp vs java
Using super in java
Multilevel inheritance : Calling order of Constructors
Abstract classes
Interfaces in java
Multiple inheritance in java
Inheritance among interfaces in java
Multiple inheritance in java
Abstract classes : cpp vs java
Abstract classes vs Interfaces
Abstract-Interface or skeletal implementations
Various interfaces
Preventing inheritance

No comments:

Post a Comment

Chitika