Java Inheritance With Examples

Java Inheritance With Examples


Inheritance In Java
  • Inheritance is the process by which one object can acquire the properties of another object.
  • This is important because it supports the concept of hierarchical classification.
  • If you think about it, most knowledge is made manageable by hierarchical (i.e., top-down) classifications.
  • For example, a Red Delicious apple is part of the classification apple, which in turn is part of the fruit class, which is under the larger class food. That is, the food class possesses certain qualities (edible, nutritious, etc.) which also, logically, apply to its subclass, fruit. In addition to these qualities, the fruit class has specific characteristics (juicy, sweet, etc.) that distinguish it from other food. The apple class defines those qualities specific to an apple (grows on trees, not tropical, etc.). A Red Delicious apple would, in turn, inherit all the qualities of all preceding classes, and would define only those qualities that make it unique.
  • Without the use of hierarchies, each object would have to explicitly define all of its characteristics.
  • Using inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent.
Note -
In the language of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the variables and methods defined by the superclass and adds its own, unique elements. 
 
Java supports inheritance by allowing one class to incorporate another class into its declaration. This is done by using the extends keyword. Thus, the subclass adds to (extends) the superclass. In other words, To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.
 
Syntax -
class subclassName extends superclassName { // body of class 
}

 
We will understand this with the help of an example we will see as follows -
 
Example - The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.
 
package javaLearnings;
// A simple example of inheritance.
// Create a superclass.
class A {
  int i, j;
  void showij() {
      System.out.println("i and j: " + i + " " + j);
  }
}
// Create a subclass by extending class A.
class B extends A {
  int k;
  void showk() {
      System.out.println("k: " + k);
  }
  void sum() {
      System.out.println("i+j+k: " + (i+j+k));
  }
}
public class Main {

  public static void main(String[] args) {
  // write your code here
      A superOb = new A();
      B subOb = new B();
// The superclass may be used by itself.
      superOb.i = 10;
      superOb.j = 20;
      System.out.println("Contents of superOb: ");
      superOb.showij();
      System.out.println();
/* The subclass has access to all public members of
its superclass. */
      subOb.i = 7;
      subOb.j = 8;
      subOb.k = 9;
      System.out.println("Contents of subOb: ");
      subOb.showij();
      subOb.showk();
      System.out.println();
      System.out.println("Sum of i, j and k in subOb:");
      subOb.sum();

  }

}

 
Output -
 
Contents of superOb:

i and j: 10 20

Contents of subOb: i and j: 7 8

k: 9

Sum of i, j and k in subOb:

i+j+k: 24
 
As you can see, subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were part of B.
 
Member Access and Inheritance
 
Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. For example, consider the following code- 
 
Example -
 
package javaLearnings;
/* In a class hierarchy, private members remain
private to their class.
This program contains an error and will not
compile.
*/
// Create a superclass.
class A {
  int i; // public by default
  private int j; // private to A
  void setij(int x, int y){
      i = x;
      j = y;
  }
}
// A's j is not accessible here.
class B extends A {
  int total;
  void sum() {
      total = i + j; // ERROR, j is not accessible here
  }
}
public class Main {

  public static void main(String[] args) {
          B subOb = new B();
          subOb.setij(10, 12);
          subOb.sum();
          System.out.println("Total is " + subOb.total);

  }
}

 
Output -

Using super to Call Superclass Constructors

A subclass can call a constructor defined by its superclass by using following super syntax - 

 

super(arg-list);


Example -

 

class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}

// A complete implementation of BoxWeight.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
164 Part I: The Java Language
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(21, 10, 25, 13.34);
BoxWeight mybox2 = new BoxWeight(3, 4, 5, 0.065);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(8, 5);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}

 

 

Advantages of Inheritance -

 
  •  Inheritance decreases the execution speed due to the increased time and effort it takes, the program to jump through all the levels of overloaded classes.
  • Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one cannot be used independently of each other.
  • The changes made in the parent class will affect the behavior of child class too.
  • The overuse of inheritance makes the program more complex. 
  • Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it.
  • Inheritance can save time and effort as the main code need not be written again.
  • Inheritance provides a clear model structure which is easy to understand.
  • An inheritance leads to less development and maintenance costs.
  • With inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs.

Final Prevents Inheritance 

You can prevent a class from being inherited by preceding its declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

Example - 

Output