Java Inheritance

In this section, you will learn about the inheritance with an example and its description.

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

Java Inheritance

                                    A hierarchy of bicycle classes.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Bicycle {
}

class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}

public class RoadBike extends Bicycle {

    // new fields and methods defining 
    // a RoadBike would go here
}

public class TandemBike extends Bicycle {

    // new fields and methods defining 
    // a TandemBike bike would go here
}

Now based on the above example, In Object Oriented terms following are true:

  • Bicycle is the superclass of MountainBike class.
  • Bicycle  is the superclass of RoadBike class.
  • RoadBike and MountainBike are sub classes of Bicycle class.
  • HondaShineBike is the subclass of both RoadBike and Bicycle  classes.

Now if we consider the IS-A relationship we can say:

  • MountainBike IS-A Bicycle
  • RoadBike IS-A Bicycle
  • HondaShineBike IS-A RoadBike
  • Hence : HondaShineBike IS-A Bicycle as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
Example:

public class Dog extends Mammal{

   public static void main(String args[]){

      Bicycle bicycle = new Bicycle();
      RoadBike roadBike = new RoadBike();
      HondaShine myBike = new HondaShine();

      System.out.println(roadBike instanceof Bicycle);
      System.out.println(myBike instanceof RoadBike);
      System.out.println(myBike instanceof Bicycle);
   }
}

This would produce following result:

Output:
true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.
Example:

public interface Bicycle{

}

public class RoadBike implements Bicycle{

}

public class HondaShine extends RoadBike{

}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether RoadBike is actually a Bicycle, and HondaShine is actually an Bicycle

public interface Bicycle{

}

public class RoadBike implements Bicycle{

}

public class HondaShine extends RoadBike{
   public static void main(String args[]){

      RoadBike roadBike = new RoadBike();
      HondaShine myBike = new HondaShine();

      System.out.println(roadBike instanceof Bicycle);
      System.out.println(myBike instanceof RoadBike);
      System.out.println(myBike instanceof Bicycle);
   }
}

This would produce following result:

output:
true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example:

public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
 private Speed sp;
} 

This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.

In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

Note: A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:

public class HondaShine extends RoadBike, Bicycle{

}

Type of Inheritances:
1. Simple Inheritance
When a subclass is derived simply from it’s parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it’s parent class. It is also called single inheritance or one level inheritance.

class A {
  int x;
  int y;
  int get(int p, int q){
    x=p; 
    y=q; 
    return(0);
  }
  void Show(){
   System.out.println(x);
  }
}

class B extends A{
  public static void main(String args[]){
  A a = new A();
  a.get(5,6);
  a.Show();
  }
  void display(){
  System.out.println("B");
  }
}

2. Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it’s parent class and this parent class works as the child class for it’s just above ( parent ) class. Multilevel inheritance can go up to any number of level.

class A {
  int x;
  int y;
  int get(int p, int q){
  x=p; y=q; return(0);
  }
  void Show(){
  System.out.println(x);
  }
}
class B extends A{
  void Showb(){
  System.out.println("B");
  }
}

class C extends B{
  void display(){
  System.out.println("C");
  }
  public static void main(String args[]){
  A a = new A();
  a.get(5,6);
  a.Show();
  }
}

3. Multiple Inheritance
Note: Java does not support multiple Inheritance.

The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.

super keyword

The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.

e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.

super.member;

Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions.

class A{
  int a;
  float b;
  void Show(){
  System.out.println("b in super class:  " + b);
  }

}

class B extends A{
  int a; 
  float b;
  B( int p, float q){
  a = p;
  super.b = q;
  }
  void Show(){
  super.Show();
  System.out.println("b in super class:  " + super.b);
  System.out.println("a in sub class:  " + a);
  }

  public static void main(String[] args){
  B subobj = new B(1, 5);
  subobj.Show();
  }
}
Output:
C:>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1

Use of super to call super class constructor:
The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command.

super(param-list);


Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list. The following program illustrates the use of the super keyword to call a super class constructor.

class A{
  int a;
  int b;
  int c;
  A(int p, int q, int r){
  a=p;
  b=q;
  c=r;
  }
}
  
  class B extends A{
  int d;
  B(int l, int m, int n, int o){
  super(l,m,n);
  d=o;
  }
  void Show(){
  System.out.println("a = " + a);
  System.out.println("b = " + b);
  System.out.println("c = " + c);
  System.out.println("d = " + d);
  }

  public static void main(String args[]){
  B b = new B(4,3,8,7);
  b.Show();
  }
  }

 

Output:
C:>java B
a = 4
b = 3
c = 8
d = 7

 

What is not possible using java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next

One Response

  1. Anonymous February 11, 2014