Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
- subclass (child) - the class that inherits from another class
- superclass (parent) - the class being inherited from
The class that inherits from another class is called the subclass, and the class that is being inherited from is called the superclass.
To inherit from a class, use the extends keyword.
Inheritance is a powerful feature of object-oriented programming (OOP) that allows one class to inherit the properties and behaviors of another class.
Example
class Animal { // field and method of the parent class String name; public void eat() { System.out.println("I can eat"); } } // inherit from Animal class Dog extends Animal { new method in subclass public void display() { System.out.println("My name is " + name); } } class Main { public static void main(String[] args) { // create an object of the subclass Dog labrador = new Dog(); // access field of superclass labrador.name = "Rohu"; labrador.display(); // call method of superclass // using object of subclass labrador.eat(); } }
In the above example, we have derived a subclass Dog from superclass Animal.
Here, labrador is an object of Dog. However, name and eat() are the members of the Animal class.
Since Dog inherits the field and method from Animal, we are able to access the field and method using the object of the Dog.
There are five types of inheritance in Java:
- Single inheritance: A subclass can inherit from only one superclass.
- Multilevel inheritance: A subclass can inherit from another subclass.
- Hierarchical inheritance: A class can have multiple subclasses, and these subclasses can inherit from each other.
- Multiple inheritance: A subclass can inherit from multiple superclasses.
- Hybrid inheritance: A combination of the above types of inheritance
benefits of using inheritance in Java:
• Reusability: Inheritance allows you to reuse the code of existing classes, which can save you time and effort.
• Modularity: Inheritance can help to make your code more modular, which can make it easier to understand and maintain.
• Extensibility: Inheritance can make your code more extensible, which means that it can be easily modified to add new features or functionality.