Java program showing concept of Inheritance


What is Inheritance?
Inheritance is a feature of Object oriented language like JAVA where child class acquires properties and methods of it's parent class.

Program

package inheritance;

public class SuperDemo
{
public void showname()
{
System.out.println("This is my SuperClass");
}
}

public class DemoClass extends SuperDemo
{
public void display()
{
System.out.println("This is subclass");
}
public static void main(String[] args)
{
DemoClass demo=new DemoClass();
demo.showname();
demo.display();
}
}


Output
This is my SuperClass
This is subclass


Explanation
  • Above is simple program showing the inheritance in Java.
  • The program declares a class named SuperDemo and one method in it.
  • the second class DemoClass extends the SuperDemo class and declares another method in it.
  • In the Main method , object of subclass i.e DemoClass is created and called the method of SuperDemo class and then the method of DemoClass.



  • Using super

  • super keyword is used to access the members of superclass directly from subclass where the members of superclass and sub class having the same name.

  • It is also used to call superclass constructor from subclass.
  • Program

    package inheritance;
    public class Expensive
    {
    int tv_price=20000;
    public void showExpense()
    {
    System.out.println("The price of tv is " + tv_price);
    }
    }

    public class NonExpensive extends Expensive
    {
    int cooler=5000;
    public void showExpense()
    {
    System.out.println("The price of cooler is " + cooler);
    }
    public void getExpense()
    {
    NonExpensive nonex=new NonExpensive();
    //call subclass method
    nonex.showExpense();
    //call superclass method
    super.showExpense();
    //get the value of tv in superclass
    int k=super.tv_price;
    System.out.println(k);
    }
    public static void main(String[] args)
    {
    NonExpensive ex=new NonExpensive();
    ex.getExpense();
    }
    }
    Output

    The price of cooler is 5000
    The price of tv is 20000
    20000


    Explanation
  • Above program declares a superclass named Expensive and a variable 'tv' and assign a value to it. A method is implemented to show the price of tv
  • A subclass named Nonexpensive extends superclass and declared a method.
  • In the method of subclass the super keyword is used to access the method and member of a superclass.
  • Java program showing concept of Inheritance  Java program showing concept of Inheritance Reviewed by LanguageExpert on August 18, 2018 Rating: 5

    No comments