Java Inheritance

 

 

  • Inheritance is one of the important feature of OOP(Object Oriented Programming).
  • It is a process in which a class is extending all the properties and behaviors of another class.
  • The properties are extended from which class known as super class or parent class.
  • The class which is extended from super class known as sub-class or child class.
  • That means the super class contains only super class properties and the sub-class contains both super class properties and sub-class properties.
  • Sub-class is created by using the keyword extends.

 

      class Vehicle
      { 
       // code
      }
      class Bike extends Vehicle
      {
      // extends the property of Vehicle class
      }

 

  • Here Bike is the sub-class and Vehicle is the super class and Bike IS-A Vehicle.
  • It provides the concept of reusability which is the main advantage of Inheritance.
  • Inheritance defines IS-A relationship between a Super class and its Sub class.


InheritanceExample1.java

package java8s;

class A1
{
      void m1()
      {
            System.out.println("java8s.com");
      }
}

class B extends A1
{
      void m2()
      {
            System.out.println("SILAN TECHNOLOGY");
      }
}

public class InheritanceExample1 {

      public static void main(String[] args) {
           
            //Case-1
                    A1 ob1=new A1();
                    ob1.m1();
                    ob1.m2();    //invalid            

            //Case-2  (Best Suitable Case)
                    B ob2=new B();
                    ob2.m1();
                    ob2.m2();
           
            //Case-3
                   A1 ob3=new B();
                   ob3.m1();
                   ob3.m2();    //invalid            

            //Case-4
                   B ob4=new A1();    //invalid

      }

}

Output
Inheritance

NOTE:
From the above 4 cases we observed that Case-2 is the best case, that means through the sub class object we can access both super and sub class properties.

 


InheritanceExample2.java

package java8s;

class A
      {
            int X;
      }
class B extends A
      {
            int Y;
            void get()
           {
             X=100:
             Y=200:
           }
           void show()
           {
             System.out.println("X="+X);
             System.out.println("Y="+Y);
           }
      }
     public class InheritanceExample2 {

           public static void main(String[] args) {
             Bobj=newB();
             obj.get();
             obj.show();
           }

           }

Output
Inheritance

NOTE:
Here from this program we observed that the sub class property can access super class property.

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment