Java Inheritance

#Java Inheritance

           Acquiring the properties from one class to another class is called as Inheritance. The properties derives form Main class (Parent) to Child class.

Available Inheritance in Java

  1. Single Inheritance
  2. Multilevel Inheritance 
  3. Hierarchical Inheritance
Multiple Inheritance is not available in Java!!

Why Multiple not avail??

      Multiple Inheritance causes dimensional problem in java program. so, the java developers cut out the Multiple inheritance from Java Programming Language.

The Following Picture Explains the Dimensional Problem.


extends is a keyword used to derive super class to sub class

Example of Single Inheritance

import java.io.*;
class Single
 {
    int a=10;
    int b=20;
    String s=hello;
  }
 class Derived extends Single
  {
      void run ()
         {
             c=a+b;
             System.out.println("The value of C is: " +c);
           }
   }
class Main
  {
           public static void main(String args[])
             {
                Derived obj = new Derived();
                obj.run();
              }
    }

Output:
The value of C is 30

Multilevel Inheritance Example:

public class Inherit_Multilevel
 {
    protected String str;
    Inherit_Multilevel()
      {
         str = "J";
       }
  }
class SubClass1 extends Inherit_Multilevel
 {
    SubClass1()
      {
         str = str.concat("A");
       }
  }
class SubClass2 extends SubClass1
  {
      SubClass2()
        {
           str = str.concat("V");
         }
    }
class SubClass3 extends SubClass2
   {  
      SubClass3()
         {
            str = str.concat("A");
         }
      void display()
         {
             System.out.println(str);
          }
    }
class MainClass
    {
        public static void main(String args[])
           {
               SubClass3 obj = new SubClass3();
               obj.display();
             }
      }


Output:
JAVA

No comments:

Post a Comment