Inheritance
Inheritance allows one class (called the child or subclass) to acquire the fields and methods of another class (called the parent or superclass). This lets the child class reuse and extend existing functionality instead of rewriting it.
1. What is Inheritance?
Inheritance allows one class (called the child or subclass) to acquire the fields and methods of another class (called the parent or superclass). This lets the child class reuse and extend existing functionality instead of rewriting it.
2. Why is it used?
It avoids duplicate code when multiple classes share common features. For example, both a Car and a Bike might share common Vehicle features like speed and fuel, which can be written once in a Vehicle class and reused by both.
3. Real-Life Example
Think of how children naturally inherit certain traits from their parents, like eye colour or height range, while also having their own unique traits. A subclass inherits features from its parent class in a similar way, while also adding its own.
4. Syntax
javaclass Parent { // fields and methods } class Child extends Parent { // additional fields and methods }
5. Example Program
javaclass Vehicle { int speed = 60; } class Car extends Vehicle { String type = "Sedan"; } public class InheritanceDemo { public static void main(String[] args) { Car car = new Car(); System.out.println("Speed: " + car.speed + ", Type: " + car.type); } }
Output:
Speed: 60, Type: Sedan6. Key Points to Remember
- The
extendskeyword is used to inherit from a parent class. - Java supports only single inheritance for classes — a class can extend only one other class directly.
- A subclass can add new fields/methods and can also override existing ones from the parent.