Inheritance in Java
Learn how to create new classes based on existing ones
💡 Think of inheritance like family traits! Just like you inherit your parents' features (like eye color or hair type), in Java, child classes can inherit properties and behaviors from parent classes. If your parent class is 'Animal', your child class 'Dog' gets all the animal features plus its own special dog features!
🌳 What is Inheritance?
Inheritance allows a class to acquire properties and methods from another class. The class that inherits is called a child/subclass, and the class being inherited from is called a parent/superclass.
// PARENT CLASS (Superclass)class Animal { String name; int age; public Animal(String name, int age) { this.name = name; this.age = age; } public void eat() { System.out.println(name + " is eating"); } public void sleep() { System.out.println(name + " is sleeping"); }}// CHILD CLASS (Subclass) - inherits from Animalclass Dog extends Animal { String breed; public Dog(String name, int age, String breed) { super(name, age); // Call parent constructor this.breed = breed; } // Dog has all Animal methods PLUS its own methods public void bark() { System.out.println(name + " says: Woof! Woof!"); }}// Using inheritanceclass InheritanceDemo { public static void main(String[] args) { Dog myDog = new Dog("Buddy", 3, "Golden Retriever"); // Dog can use Animal methods (inherited) myDog.eat(); // From Animal class myDog.sleep(); // From Animal class // Dog can use its own methods myDog.bark(); // From Dog class System.out.println("Name: " + myDog.name); // Inherited field System.out.println("Breed: " + myDog.breed); // Own field }}❓ Why Use Inheritance?
- ✓Code Reusability: Write code once, use it in multiple classes
- ✓Organization: Group related classes together in a hierarchy
- ✓Extensibility: Add new features to existing code without changing it
- ✓Polymorphism: Treat different objects in similar ways (we'll learn more about this!)
🔄 Method Overriding
class Vehicle { String brand; int speed; public Vehicle(String brand) { this.brand = brand; this.speed = 0; } // Parent method public void start() { System.out.println("Vehicle is starting..."); } public void displayInfo() { System.out.println("Brand: " + brand); System.out.println("Speed: " + speed + " km/h"); }}class Car extends Vehicle { int numberOfDoors; public Car(String brand, int doors) { super(brand); // Call parent constructor this.numberOfDoors = doors; } // OVERRIDE parent method - provide own version @Override public void start() { System.out.println("Car engine starting... Vroom!"); super.start(); // Can still call parent version if needed } // Child can have its own methods too public void honk() { System.out.println("Beep beep!"); }}class Motorcycle extends Vehicle { boolean hasSidecar; public Motorcycle(String brand, boolean sidecar) { super(brand); this.hasSidecar = sidecar; } // OVERRIDE - Motorcycle starts differently than Car @Override public void start() { System.out.println("Motorcycle engine revving... Brrrm!"); }}class OverrideDemo { public static void main(String[] args) { Car myCar = new Car("Toyota", 4); Motorcycle myBike = new Motorcycle("Harley", false); // Each calls its own overridden version! myCar.start(); // "Car engine starting... Vroom!" myBike.start(); // "Motorcycle engine revving... Brrrm!" myCar.honk(); // Car's own method }}⬆️ Using super Keyword
class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public void introduce() { System.out.println("Hi, I'm " + name); }}class Student extends Person { String studentId; double gpa; public Student(String name, int age, String id, double gpa) { // MUST call parent constructor first! super(name, age); // Calls Person constructor this.studentId = id; this.gpa = gpa; } @Override public void introduce() { // Call parent's introduce first super.introduce(); // Add student-specific information System.out.println("I'm a student with ID: " + studentId); System.out.println("My GPA is: " + gpa); } public void study() { System.out.println(name + " is studying"); // Can access parent's fields }}class SuperDemo { public static void main(String[] args) { Student alice = new Student("Alice", 20, "S12345", 3.8); alice.introduce(); // Output: // Hi, I'm Alice (from parent) // I'm a student with ID: S12345 (from child) // My GPA is: 3.8 (from child) alice.study(); }}🔗 Types of Inheritance in Java
1. Single Inheritance
One child class inherits from one parent class
Dog extends Animal
2. Multilevel Inheritance
Child class inherits from another child class
Puppy extends Dog extends Animal
3. Hierarchical Inheritance
Multiple child classes inherit from one parent
Dog, Cat, Bird all extend Animal
// SINGLE INHERITANCEclass Animal { void eat() { System.out.println("Eating..."); }}class Dog extends Animal { void bark() { System.out.println("Barking..."); }}// MULTILEVEL INHERITANCEclass Puppy extends Dog { void play() { System.out.println("Playing..."); }}// HIERARCHICAL INHERITANCEclass Cat extends Animal { void meow() { System.out.println("Meowing..."); }}class Bird extends Animal { void fly() { System.out.println("Flying..."); }}class TypesDemo { public static void main(String[] args) { // Single: Dog inherits from Animal Dog dog = new Dog(); dog.eat(); // From Animal dog.bark(); // Own method // Multilevel: Puppy inherits from Dog, Dog inherits from Animal Puppy puppy = new Puppy(); puppy.eat(); // From Animal (grandparent) puppy.bark(); // From Dog (parent) puppy.play(); // Own method // Hierarchical: Cat and Bird both inherit from Animal Cat cat = new Cat(); cat.eat(); // From Animal cat.meow(); // Own method Bird bird = new Bird(); bird.eat(); // From Animal bird.fly(); // Own method }}🌟 Real-World Example: Employee System
// Base class for all employeesclass Employee { protected String name; protected String employeeId; protected double baseSalary; public Employee(String name, String id, double salary) { this.name = name; this.employeeId = id; this.baseSalary = salary; } public void work() { System.out.println(name + " is working"); } public double calculateSalary() { return baseSalary; } public void displayInfo() { System.out.println("Name: " + name); System.out.println("ID: " + employeeId); System.out.println("Salary: $" + calculateSalary()); }}// Specialized employee typesclass Developer extends Employee { private String programmingLanguage; private int projectsCompleted; public Developer(String name, String id, double salary, String language) { super(name, id, salary); this.programmingLanguage = language; this.projectsCompleted = 0; } @Override public void work() { System.out.println(name + " is coding in " + programmingLanguage); } public void completeProject() { projectsCompleted++; System.out.println("Project completed! Total: " + projectsCompleted); } @Override public double calculateSalary() { // Developers get bonus for each project return baseSalary + (projectsCompleted * 1000); }}class Manager extends Employee { private int teamSize; private double bonus; public Manager(String name, String id, double salary, int teamSize) { super(name, id, salary); this.teamSize = teamSize; this.bonus = 0; } @Override public void work() { System.out.println(name + " is managing a team of " + teamSize); } public void giveBonus(double amount) { this.bonus = amount; } @Override public double calculateSalary() { // Managers get base salary plus bonus return baseSalary + bonus; }}class EmployeeDemo { public static void main(String[] args) { Developer dev = new Developer("Alice", "DEV001", 80000, "Java"); Manager mgr = new Manager("Bob", "MGR001", 100000, 5); // Each works differently dev.work(); // "Alice is coding in Java" mgr.work(); // "Bob is managing a team of 5" // Update their stats dev.completeProject(); dev.completeProject(); mgr.giveBonus(15000); // Display info with calculated salaries System.out.println("\n--- Developer Info ---"); dev.displayInfo(); // Salary includes project bonuses System.out.println("\n--- Manager Info ---"); mgr.displayInfo(); // Salary includes bonus }}🔑 Key Concepts
extends Keyword
Used to create a child class from a parent class
class Dog extends Animal { }
super Keyword
Used to call parent class constructor or methods
super(); or super.methodName();
Method Overriding
Child class provides its own version of parent's method
@Override public void sound() { ... }
IS-A Relationship
Child IS-A type of Parent
Dog IS-A Animal, Car IS-A Vehicle
✨ Best Practices
- ✓Use inheritance for IS-A relationships only (Dog IS-A Animal)
- ✓Keep inheritance hierarchies shallow (2-3 levels max)
- ✓Use @Override annotation when overriding methods
- ✓Call super() as first line in child constructor if needed
- ✓Don't inherit just to reuse code - prefer composition for HAS-A relationships
💼 Interview Tips
- •Java supports single inheritance only (one parent class)
- •Java doesn't support multiple inheritance with classes (but does with interfaces)
- •All classes in Java inherit from Object class by default
- •Private members are not inherited, but can be accessed through public methods
- •Constructors are not inherited but can be called using super()