In Java, inheritance allows a subclass (child class) to reuse features from a superclass (parent class). The key features reused through inheritance are:
- Attributes (fields) : The subclass inherits variables (fields) defined in the superclass, such as properties or state information. For example, a
Car
class can inherit thebrand
attribute from aVehicle
class
- Methods : The subclass inherits methods (functions) defined in the superclass, allowing it to use or override these behaviors. For instance, a subclass can call a method like
honk()
defined in its superclass
- Constructors (via
super
): While constructors are not inherited per se, a subclass can reuse the superclass constructor by calling it withsuper()
, enabling initialization of inherited attributes
- Access to protected members : Members declared
protected
in the superclass are accessible to subclasses, facilitating reuse while maintaining encapsulation
In summary, inheritance in Java enables subclasses to reuse the attributes and methods of their superclass, promoting code reusability, reducing redundancy, and allowing hierarchical class relationships