Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to define a new class based on an existing class. In Java, inheritance enables you to create a hierarchy of classes where a subclass inherits the characteristics (fields and methods) of its super class. The subclass can then extend or modify the inherited behavior, as well as add new fields and methods specific to itself.
To establish an inheritance relationship between classes in Java, you use the extends keyword. Here's an example:
In this example, the class Animal is the super class, and the class Dog is the subclass. The Dog class extends the Animal class, which means it inherits the eat() method from the Animal class. Additionally, the Dog class introduces a new method bark() that is specific to dogs.
You can create an instance of the Dog class and call its inherited and own methods:
In this code, the dog object can invoke both the inherited eat() method from the Animal class and the bark() method defined in the Dog class.
Inheritance allows you to establish an "is-a" relationship between classes, where a subclass is considered to be a more specialized version of its super class. It promotes code reuse, as common behavior and characteristics can be defined in the super class and inherited by multiple sub classes. In Java, a class can only directly inherit from a single super class, but it can implement multiple interfaces using the implements keyword to achieve multiple inheritance-like behavior.
Read More...
Java Course in Ahmednagar | Java Classes in Ahmednagar | Java Training in Ahmednagar