Friday, 25 November 2016

Program to show simple example of inheritance

Inheritance is the property in which objects of one class acquires the properties of other class. This is the one of feature Java which is known as Reusability .With the use of inheritance, the information is made manageable in a hierarchical order. A class that is inherited is called a superclass. The class that does the inheriting is called subclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements. There are following types of Inheritance:
  1. Single Inheritance (only one superclass and subclass)
  2. Multilevel Inheritance (subclass is super class of another class)
  3. Hierarchical Inheritance (one super class with many subclasses)
  4. Multiple Inheritance (several super classes for a subclass)
  5. Hybrid Inheritance (combination of above three types)
Java supports the first three types of inheritance. Java does not support Multiple inheritance and hybrid inheritance. Java does not directly implement the multiple inheritance. This is implemented using the concept of interface. The syntax of single inheritance is given below:
class <superclass-name> {
    // Body of superclass
}

class <subclass-name> extends <superclass-name> {
 // Body of subclass
}

This a program for the single inheritance, in that A1 is a superclass which has two variable i, j and one method showij( ). Next the class A1 is get inherited in class B1 which have one variable k and two methods showk( ), sum( ). Now in SingleInhDemo2 class we have created an object A1 and B1 classes, initialized the data members and called the methods of classes. Note that after compiling the SingleInhDemo2.java file the three .class files will be created "A1.class", "B1.class" and "SingleInhDemo2.class".


PROGRAM
//Create a superclass.

class A1 {
 int i, j;
 void showij() {
  System.out.println("i and j: " + i + " " + j);
 }
}

//Create a subclass by extending class A1.
class B1 extends A1 {
 int k;
 void showk() {
  System.out.println("k: " + k);
 }
 void sum() {
  System.out.println("i+j+k: " + (i+j+k));
 }
}

public class SingleInhDemo2 {

 public static void main(String[] args) {

  A1 superOb = new A1();
  B1 subOb = new B1();

  // 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
C:\>javac SingleInhDemo2.java
C:\>java SingleInhDemo2
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

No comments:

Post a Comment