๐ฅInheritance
๐ช What is Inheritance?
Inheritance in Java allows a class to inherit attributes and behaviors from another class. This promotes code reuse and establishes hierarchical relationships between classes.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
๐ก Rules for Inheritance in Java ๐จโ๐ป
Inheritance in Java follows these main rules:
๐ข Uses "extends" keyword to inherit from superclass
๐ก Subclasses inherit public and protected members
๐ด Private members not inherited
๐ฃ Single inheritance - one superclass allowed
๐ข Subclass can override superclass methods
๐ก Overridden methods must have same signature
๐ข Use super() to call superclass constructor
๐ข Subclass can declare new members
๐ก Subclass can reuse superclass code
๐ต Inheritance represents an "is-a" relationship
๐ฃ Use interfaces for "has-a" relationship
๐ด Avoid overusing inheritance where aggregation works better
Inheritance enables code reuse and establishes rich relationships between classes. But careful design is needed to maximize benefits.
๐จโ๐ฆ Parent and Child Classes
In Java, classes can inherit from other classes using the extends
keyword:
Here Car
inherits from the Vehicle
class.
๐ Key Notes
Inheritance allows a class to inherit from another parent class
The child class gets all the members of the parent class
This establishes a hierarchical parent-child relationship
Inheritance supports code reuse in Java
So with inheritance, classes can reuse logic in other classes!
๐จโ๐ฆ In Simple Terms
Inheritance allows classes to form hierarchical parent-child relationships, just like children inherit genes and traits from their parents.
The child class automatically gets the fields and methods of the parent class, allowing code reuse.
So in Java, inheritance represents parent-child class relationships!
Last updated