What is Inheritance in Java?

Inheritance is an important feature of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.
Important terminology:
  • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Syntax of Inheritance:

class SubclassName extends SuperclassName  
{  
   //methods and fields  
}  


The extends keyword is used to create a new class that derives from an existing class.

Let us see how extends keyword is used to achieve Inheritance.
class Vehicle.
{
  ......
}
class Car extends Vehicle
{
 .......   //extends the property of vehicle class.
}

Now based on above example. In OOPs term we can say that,
  • Vehicle is super class of Car.
  • Car is sub class of Vehicle.
  • Car IS-A Vehicle.

Simple example of Inheritance

class Parent
{
    public void p1()
    {
        System.out.println("Parent method");
    }
}
public class Child extends Parent {
    public void c1()
    {
        System.out.println("Child method");
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.c1();   //method of Child class
        cobj.p1();   //method of Parent class
    }
}

Output: Child method Parent method

Click here to find complete Java Tutorials Series



Java OOPS   << Previous     ||     Next >>   Java Encapsulation

Popular posts from this blog

Top 7 Web Development Trends in the Market

Mastering Selenium Practice: Automating Web Tables with Demo Examples

25+ Selenium WebDriver Commands: The Complete Cheat Sheet with Examples

Top 10 Highest Paid Indian-Origin CEOs in the USA

Top 11 Interview Blunders That Can Cost You the Job: Expert Tips to Avoid Them

Applications of Artificial Intelligence in Healthcare

Top 10 Demo Websites for Selenium Automation Practice

14+ Best Selenium Practice Exercises to Master Automation Testing

Tosca Automation Testing Tool: A Comprehensive Guide for Testers

Top 20 Selenium Interview Questions & Answers