Skip to content

OOP Inheritance Introduction#

What Is The Inheritance In OOP?#

  • Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOP.
  • The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
  • Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
  • Using inheritance in Java will help us:

Java Inheritance Syntax#

  • The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.
  • In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Inheritance Example#

  • Let's define a parent class Animal as below
Animal.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    package com.java.core.inheritance;

    public class Animal {

            private String name;

            public void eat() {
                    System.out.println("eating...");
            }

            public void sleep() {
                    System.out.println("sleeping at forest!");
            }

            public String getName() {
                    return name;
            }

            public void setName(String name) {
                    this.name = name;
            }
    }
  • Then create a subclass which is extends from Animal
Dog.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    package com.java.core.inheritance;

    public class Dog extends Animal {

            public void bark() {
                    System.out.println("barking...");
            }

            @Override
            public void sleep() {
                    System.out.println("sleeping at human's house!");
            }

    }
  • Now, test the child class Dog and you will see the child class can inherit attribute name and method eat from parent class Animal. Moreover, It is also @Override the method sleep() from it's parent.
JavaInheritanceMain.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    package com.java.core.inheritance;  

    public class JavaInheritanceMain {  

            public static void main(String[] args) {  
                    Dog dog = new Dog();  
                    dog.setName("Bulldog");  

                    System.out.println(dog.getName());  
                    dog.eat();  
                    dog.bark();  
                    dog.sleep();  
            }
    }
1
2
3
4
Bulldog
eating...
barking...
sleeping at human's house!

See Also#

References#