Java Inheritance

Introduction

Java Inheritance can create a hierarchical classes.

Java class that is inherited is called a superclass.

The class that does the inheriting is called a subclass.

A subclass is a specialized version of a superclass.

It inherits all of the members defined by the superclass and can add its own elements.

Syntax

To inherit a class, use the extends keyword.

The general form of a class declaration that inherits a superclass is shown here:

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

The following program creates a superclass called A and a subclass called B.

// Create a superclass.
class A {/*  www . ja  v a  2  s.c om*/
  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[]) {
    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();
  }
}

The subclass B includes all of the members of its super class A.

Java does not support the inheritance of multiple super classes.

A Java class cannot be a superclass of itself.




PreviousNext

Related