Inheritance is a mechanism in Java that allows a class to inherit properties and behaviors from another class. When a class extends another class, it is said to inherit from that class. The class that is being inherited from is called the superclass, and the class that is inheriting is called the subclass.
Here is an example of inheritance in Java:
class Animal { // Properties and methods of the Animal class } class Dog extends Animal { // Properties and methods of the Dog class }
In this example, the Dog
class is a subclass of the Animal
class. The Dog
class inherits all of the properties and methods of the Animal
class, as well as any properties and methods defined specifically in the Dog
class.
One of the main benefits of inheritance is that it allows you to reuse code and avoid duplication. For example, if the Animal
class has a breathe()
method that is common to all animals, you can use this method in the Dog
class without having to re-implement it.
In addition to inheritance, Java also supports polymorphism, which allows a subclass to override or extend the behavior of a superclass method. This allows a subclass to have its own implementation of a method inherited from the superclass, while still maintaining the same method signature.
For more information on inheritance and polymorphism in Java, you can refer to the Java documentation.