Single Inheritance in Java


Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. Inheritance is a basic object oriented feature in which one class acquires and extends upon the properties of another class, using the keyword extends.

With the use of the extends keyword among classes, all the properties of the superclass (also known as the Parent Class or Base Class) are present in the subclass (also known as the Child Class or Derived Class)

Types of Inheritance :

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance

Single Inheritance
      Single inheritance is one base class and one derived class. One in which the derived class inherits the one base class either publicly, privately or protected

Syntax:
      class baseclass_Name
      {
            superclass data variables ;
            superclass member functions ;
      }
      class derivedclass_Name extends baseclass _Name
      {
            subclass data variables ;
            subclass member functions ;
      }

This program demonstrates single inheritance in Java, where one class inherits from another class.

  • The program has two classes - Father and Son. Son is derived from Father using the extends keyword, making it a subclass or derived class, and Father is the superclass or base class.
  • Father class has a single method named house(), which prints out "Have Own 2BHK House."
  • Son class has a single method named car(), which prints out "Have Own Audi Car."
  • In the main function, an object of Son class is created, and the car() and house() methods are called on it. Since Son class is derived from Father, it has access to all the public and protected members of Father. Hence, Son class can call the house() method of Father class using the super keyword.

Source Code

//Single Inheritance in Java
class Father //Base
{
    public void house()
    {
        System.out.println("Have Own 2BHK House.");
    }
}
class Son extends Father //Derived
{
    public void car()
    {
        System.out.println("Have Own Audi Car.");
    }
}
 
public class single {
    public static void main(String args[])
    {
        Son o =new Son();
        o.car();
        o.house();
    }
}
 

Output

Have Own Audi Car.
Have Own 2BHK House.
To download raw file Click Here

Basic Programs