Concept Explanation
Inheritance allows one class to inherit the attributes and methods of another.
- Superclass (Parent): The class being inherited from.
- Subclass (Child): The class that inherits.
Think of it like a Family Tree. A "Parent" has traits (like eye color). The "Child" inherits those traits but can also have their own unique traits (like a specific talent).
Syntax or Core Structure
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
// Car inherits from Vehicle
class Car extends Vehicle {
private String modelName = "Mustang";
}
The 'super' Keyword
If you want to call a method or a constructor from the parent class, use super.
public Car() {
super(); // Calls the Vehicle constructor
}
Common Mistakes
- Multiple Inheritance: Java does NOT allow a class to inherit from two parents (
class Car extends Vehicle, Machineis illegal). You must use Interfaces for that. - Private variables: Subclasses can't see
privatevariables of the parent. Useprotectedif you want the child to have access.
Practice Exercises
- The Employee System: Create a parent class
Employee(Name, ID) and a subclassDeveloper(ProgrammingLanguage). - The Shape Family: Create a
Shapeclass with acolorattribute. Create aCirclesubclass with aradius. - Method Overriding: Research
@Override. Create a parent methodmakeSound()and override it in a child class to produce a specific sound.