Extends Keyword
Inheritance with extends
Inheritance allows a class to inherit fields and methods from another class.
Basic Inheritance
// Parent class (superclass)
public class Animal {
String name;
int age;
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (subclass)
public class Dog extends Animal {
String breed;
public void bark() {
System.out.println(name + " is barking");
}
}
// Usage
Dog dog = new Dog();
dog.name = "Rex"; // Inherited from Animal
dog.breed = "Labrador";
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
What is Inherited?
public class Parent {
public int x = 10; // Inherited
protected int y = 20; // Inherited
int z = 30; // Inherited (if same package)
private int w = 40; // NOT inherited
public void publicMethod() { } // Inherited
protected void protectedMethod() { } // Inherited
void defaultMethod() { } // Inherited
private void privateMethod() { } // NOT inherited
}
public class Child extends Parent {
public void test() {
System.out.println(x); // OK
System.out.println(y); // OK
System.out.println(z); // OK
// System.out.println(w); // ERROR!
publicMethod(); // OK
// privateMethod(); // ERROR!
}
}
IS-A Relationship
// Dog IS-A Animal (inheritance)
// Cat IS-A Animal (inheritance)
Dog dog = new Dog();
Animal animal = dog; // OK - Dog IS-A Animal
// Animal animal = new Animal();
// Dog dog = animal; // ERROR - Animal is NOT necessarily a Dog
Super Keyword
The super Keyword
super refers to the parent class.
Accessing Parent Methods
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
@Override
public void eat() {
super.eat(); // Call parent's eat()
System.out.println("Dog is eating");
}
}
Dog dog = new Dog();
dog.eat();
// Output:
// Animal is eating
// Dog is eating
Accessing Parent Fields
public class Parent {
int x = 10;
}
public class Child extends Parent {
int x = 20; // Shadows parent's x
public void printX() {
System.out.println(x); // 20 (child's)
System.out.println(super.x); // 10 (parent's)
}
}
Calling Parent Constructor
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}
public class Dog extends Animal {
String breed;
public Dog(String name, String breed) {
super(name); // Must be first statement
this.breed = breed;
}
}
super() vs this()
public class Example {
public Example() {
this(10); // Call another constructor in THIS class
// super(); // ERROR - can't have both!
}
public Example(int x) {
super(); // Call parent constructor
// this(); // ERROR - can't have both!
}
}
Constructor Chaining in Inheritance
Constructor Chaining
When creating a child object, parent constructor runs first.
Constructor Execution Order
public class Grandparent {
public Grandparent() {
System.out.println("Grandparent constructor");
}
}
public class Parent extends Grandparent {
public Parent() {
System.out.println("Parent constructor");
}
}
public class Child extends Parent {
public Child() {
System.out.println("Child constructor");
}
}
// When: new Child()
// Output:
// Grandparent constructor
// Parent constructor
// Child constructor
With super()
public class Animal {
String name;
public Animal(String name) {
this.name = name;
System.out.println("Animal: " + name);
}
}
public class Dog extends Animal {
String breed;
public Dog(String name, String breed) {
super(name); // Must be first!
this.breed = breed;
System.out.println("Dog: " + breed);
}
}
// new Dog("Rex", "Labrador")
// Output:
// Animal: Rex
// Dog: Labrador
Complete Chain
public class A {
public A() { System.out.println("A"); }
}
public class B extends A {
public B() { System.out.println("B"); }
}
public class C extends B {
public C() { System.out.println("C"); }
}
// new C() prints: A, B, C
With Parameters
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Employee extends Person {
String company;
public Employee(String name, int age, String company) {
super(name, age);
this.company = company;
}
}
Types of Inheritance
Inheritance Types
Single Inheritance
// A -> B
public class Animal { }
public class Dog extends Animal { }
Multilevel Inheritance
// A -> B -> C
public class Animal { }
public class Dog extends Animal { }
public class Puppy extends Dog { }
Hierarchical Inheritance
// A -> B, A -> C
public class Animal { }
public class Dog extends Animal { }
public class Cat extends Animal { }
Java Does NOT Support
// Multiple inheritance with classes (NOT allowed)
// class C extends A, B { } // COMPILE ERROR!
// But interfaces allow it:
// class C implements InterfaceA, InterfaceB { } // OK
When to Use Inheritance
// USE inheritance when:
// - Clear IS-A relationship
// - Child truly is a type of parent
// - Sharing common behavior
// Don't use when:
// - Just for code reuse
// - No clear IS-A relationship
// - Using HAS-A would be better
// Example:
// Dog IS-A Animal ✓
// Car IS-A Engine ✗ (Car HAS-A Engine)
Practice Problems
Design an in-memory file system with directories and files.
Example:
Input: mkdir('/a'), addContentToFile('/a/b', 'content')
Output: null
File system operations
Optimal Solution — O(n) for path operations time, O(n) space
Use Trie-like structure with Directory and File classes.
class FileSystem {
class Entry { }
class File extends Entry { String content; }
class Directory extends Entry { Map<String, Entry> children; }
private Directory root;
public FileSystem() { root = new Directory(); root.children = new HashMap<>(); }
}Edge Cases:
- Root directory
- Nested paths
- File already exists
Design a parking lot system.
Example:
Input: parkVehicle(1), getAvailableSpots()
Output: n-1
Track parking spots
Optimal Solution — O(1) for park/unpark time, O(n) space
Use inheritance for vehicle types.
class ParkingLot {
class Vehicle { String plate; }
class Car extends Vehicle { }
class Truck extends Vehicle { }
private int capacity;
private List<Vehicle> parked;
}Edge Cases:
- Full lot
- Invalid vehicle
- Remove non-existent
Design an employee system with different employee types.
Example:
Input: new Manager("Alice", 100000)
Output: Manager
Different employee types
Optimal Solution — O(1) time, O(1) space
Use abstract base class with subclasses.
abstract class Employee {
String name;
double salary;
abstract double calculateBonus();
}
class Manager extends Employee {
double calculateBonus() { return salary * 0.2; }
}
class Developer extends Employee {
double calculateBonus() { return salary * 0.1; }
}Edge Cases:
- Different bonus rates
- Negative salary
- Null name
Quiz
1. Which keyword is used for inheritance?
2. What does super() do?
3. Does Java support multiple inheritance with classes?
4. What runs first when creating a child object?
Flashcards
Question
What is inheritance?
Click to reveal answer
Answer
A mechanism where a child class acquires fields and methods from a parent class using 'extends'.
Question
What is the IS-A relationship?
Click to reveal answer
Answer
A relationship where child IS-A type of parent. Dog IS-A Animal.
Question
What is the diamond problem?
Click to reveal answer
Answer
A problem with multiple inheritance where a class inherits from two classes that have a common ancestor. Java avoids this by not supporting multiple class inheritance.
Question
When does parent constructor execute?
Click to reveal answer
Answer
Before child constructor. Order: Grandparent -> Parent -> Child.
Question
What is Inheritance?
Click to reveal answer
Answer
Inheritance is a key concept in Java programming.
Revision Notes
Key Takeaways
- 1.Inheritance promotes code reuse
- 2.super() must be first in constructor
- 3.Parent constructor runs first
- 4.Java supports single inheritance only
Interview Tips
- •Know when to use inheritance vs composition
- •Understand constructor chaining order
- •Practice designing class hierarchies
- •Know limitations of Java inheritance
Cheat Sheet
Cheat Sheet
- extends: inherit from parent
- super: reference to parent
- super(): call parent constructor
- IS-A: Dog IS-A Animal
- Single: A -> B
- Multilevel: A -> B -> C
- Hierarchical: A -> B, A -> C