Java Class Inheritance

In this chapter you will learn:

  1. What is class inheritance
  2. Example - Java Class Inheritance

Description

In Java the classes can inherit attributes and behavior from pre-existing classes. The pre-existing classes are called base classes, superclasses, or parent classes. The new classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance form a hierarchy.

Example

Let's look at an example. Suppose we have a class called Employee. It defines first name, last name. Then we want to create a class called Programmer. Programmer would have first name and last name as well. Rather than defining the first name and last name again for Programmer we can let Programmer inherit from Employee. In this way the Programmer would have attributes and behavior from Employee.

To inherit a class, you can use the extends keyword.

The following program creates a superclass called Base and a subclass called Child.

 
class Base {//w  ww  .  java2 s . c  o m
  int i, j;
  void showBase() {
    System.out.println("i and j: " + i + " " + j);
  }
}
class Child extends Base {
  int k;
  void showChild() {
    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[]) {
    Base superOb = new Base();
    Child subOb = new Child();

    superOb.i = 10;
    superOb.showBase();
    System.out.println();

    subOb.i = 7;
    subOb.showBase();
    subOb.showChild();
    System.out.println();

    subOb.sum();
  }
}

The output from this program is shown here:

The subclass Child includes all of the members of its superclass. The general form of a class declaration that inherits a superclass is shown here:


class subclass-name extends superclass-name { 
   // body of class 
}

You can only have one superclass for any subclass. Java does not support the multiple inheritance. A class can be a superclass of itself.

Next chapter...

What you will learn in the next chapter:

  1. What is super keyword
  2. How to use super to call superclass constructors
  3. How to use super to reference members from parent class