What is inheritance In Java





Inheritance is one of the important mechanisms of OOPs(Object-Oriented Programming Systems) in java. It is a mechanism in which one object acquires all the properties of its parent object.
  • It is basically used for code reusability in java.
  • The concept behind inheritance in java is that you can create new classes that will contain all the properties of its parent class.
  • When you inherit a class named A in another class named B then you can access all the methods of class A in class B.
  • In java, it is used to achieve runtime polymorphism.
  • Multiple inheritances in java are not possible through the class because of the diamond problem.
  • Inheritance in java is used in method overriding also.
  • Inheritance is also known as IS-A relationship in java which basically means parent-child relationship.

What is the use of inheritance in java-

  • In java, inheritance is basically used for code reusability.
  • It is basically used to achieve runtime polymorphism in object-oriented programming.

Main keywords used in inheritance-

Class-
  • It is basically known as the collection of objects.
  • It represents or contains the methods that are common to all objects of similar type.
Sub Class/Child Class-
  • Sub Class/Child Class is the class that inherits the other class(known as the parent class) in java.
Super Class/Parent Class-
  • The class which is inherited by child class is known as Super Class in Java.

Syntax of inheritance in Java-

1-  class Subclassname extends Superclassname{
2- //Methods, variables or fields
3-   }

The extends keyword here indicates that we are creating a new class from the existing class

Example of inheritance in Java-

1- package Java_Test;
2- class Superclass{
3- public void A() {
4- System.out.println("Method A");
5- }
6- }
7- class Subclass extends Superclass{
8- public void B() {
9- System.out.println("Method B");
10- }
11- }
12- public class Inheritance_In_Java {
13- public static void main(String[] args) {
14- Subclass obj=new Subclass();
15- obj.A();
16- obj.B();
17- }
18- }