🧠 Java Quiz

Java Inheritance

Build new classes that reuse and extend the behavior of existing ones.

The basics

Use extends to make one class inherit from another. The new class (subclass) automatically gets all non-private fields and methods of the parent (superclass).

Animal → Dog
class Animal {
    String name;

    public void eat() {
        System.out.println(name + " is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println(name + " says Woof!");
    }
}

Dog d = new Dog();
d.name = "Rex";
d.eat();    // inherited from Animal: "Rex is eating"
d.bark();   // defined in Dog:        "Rex says Woof!"

The super keyword

super refers to the parent class. Use it to call the parent's constructor or access overridden methods.

Calling super
class Animal {
    String name;
    public Animal(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    String breed;
    public Dog(String name, String breed) {
        super(name);          // call Animal's constructor
        this.breed = breed;
    }
}

Dog d = new Dog("Rex", "Labrador");

Method overriding

A subclass can replace an inherited method's behavior. Annotate it with @Override — the compiler will then catch typos.

@Override
class Animal {
    public void speak() {
        System.out.println("Some generic sound");
    }
}

class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    @Override
    public void speak() {
        System.out.println("Meow!");
    }
}

Animal a = new Dog();
a.speak();   // "Woof!" — runtime decides based on actual type

The Object class

Every class in Java implicitly extends java.lang.Object. That's why every object has methods like toString(), equals(), and hashCode().

Overriding toString
class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name; this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" + name + ", " + age + "}";
    }
}

System.out.println(new Person("Raman", 28));
// Person{Raman, 28}

Single inheritance

A class can extend only one superclass. Java doesn't have multiple inheritance for classes (it does allow implementing multiple interfaces — covered later).

final classes — preventing inheritance

If a class shouldn't be extended, mark it final. String, Integer, and other core classes are final.

final class
final class Configuration {
    // nobody can extend this
}
"Favor composition over inheritance" Inheritance is powerful but can make code rigid. When a class doesn't naturally "is-a" the parent, prefer "has-a" — hold the other class as a field instead of extending it.