Inheritance In Java | Subclass and Superclass | Java For Beginner | Extends Keyword | OOPs.



Inheritance 

Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. The Object of one class Acquired the properties of object of another class is called inheritance.

In the terminology 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 instance variables and methods defined by the superclass and adds its own, unique elements.

To inherit a class, you simply incorporate the definition of one class into another by using
the extends keyword.


 class subclassname extends superclassname
 {
    variable declaratin;
    methods declaration;
 }


The keyword extends signifies that the properties of the superclassname are extended to the subclassname.

The subclass will now contain its own variables and methods as well as those of the superclass.




Types of Inheritance :-

  1. Single Inheritance ,
  2. Multilevel Inheritance and 
  3. Hierarchical inheritance.
In Java Only this Three types of Inheritance is Supported.



Multiple inheritance and Hybrid inheritance is not supported in java through class.


Why use inheritance in java?
  1. For Method Overriding (so runtime polymorphism can be achieved).
  2. For Code Reusability.

Simple Program 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));
   }
}
class SimpleInheritance
{
   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();

      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

Post a Comment

1 Comments