Skip to main content

Java OOP

Inheritance

Complete lesson for Inheritance using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Inheritance

Section: Java OOP. extends, the five types of inheritance with real-life examples, visibility of parent members, super, constructor chaining, overriding, and IS-A vs HAS-A.

What is inheritance?

  • Inheritance lets a new class (child) reuse the fields and methods of an existing class (parent) and add its own.
  • In Java you write class Child extends Parent. The child IS-A parent: a Dog is an Animal.
  • Real life: a child inherits a surname, eye colour, and family house from the parents, and also has a personal skill of their own.
  • The child gets everything the parent offers (subject to access rules), can add new members, and can change (override) inherited behaviour.
  • Every Java class inherits from java.lang.Object, directly or indirectly.
TermAlso calledMeaning
SuperclassParent class, base classThe class being inherited from
SubclassChild class, derived classThe class that inherits
extendsInheritance keywordConnects a child class to one parent class
implementsInterface keywordConnects a class to one or more interfaces
superParent referenceCalls the parent constructor, method, or field
IS-AInheritance relationshipDog IS-A Animal, Car IS-A Vehicle
OverridingRuntime polymorphismChild gives a new body to an inherited method
class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }

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

class Dog extends Animal {          // Dog IS-A Animal
    Dog(String name) {
        super(name);                // call the parent constructor first
    }

    void bark() {                   // new method only in Dog
        System.out.println(name + " is barking");
    }
}

public class InheritDemo {
    public static void main(String[] args) {
        Dog d = new Dog("Tommy");
        d.eat();  // inherited from Animal
        d.bark(); // own method
    }
}

Why use inheritance?

  • Code reusability: write common code once in the parent and reuse it in every child.
  • Less duplication: a fix in the parent is applied to all children.
  • Extensibility: add new child classes without changing existing, tested code.
  • Polymorphism: a parent reference can hold any child object, so one method can work with many types.
  • Natural modelling: real-world "is a kind of" relationships (Car is a Vehicle, Manager is an Employee) map directly to classes.

Types of inheritance in Java

  • With classes Java supports single, multilevel, and hierarchical inheritance.
  • Multiple and hybrid inheritance are not allowed with classes, but are achieved with interfaces.
TypeShapeSimple real-life exampleSupported in Java?
SingleA -> BMobile -> SmartPhoneYes, with extends
MultilevelA -> B -> CGrandFather -> Father -> SonYes, with extends in a chain
HierarchicalA -> B, A -> C, A -> DEmployee -> Manager, Developer, TesterYes, many classes extend one parent
MultipleA, B -> CCamera, MusicPlayer, Phone -> SmartPhoneNot with classes; yes with implements A, B
HybridMix of the aboveVehicle -> Car -> HybridCar + Electric, PetrolYes, using classes plus interfaces

Types of inheritance in Java — with real-life examples

Classes support single, multilevel, and hierarchical inheritance with extends. Multiple and hybrid inheritance need interfaces with implements, because a class can extend only one class.

Java inheritance types infographic: single (SmartPhone extends Mobile), multilevel (Son extends Father extends GrandFather), hierarchical (Manager, Developer and Tester extend Employee), multiple through interfaces (SmartPhone implements Camera, MusicPlayer, Phone), hybrid (HybridCar extends Car extends Vehicle and implements Electric and Petrol), and multiple class inheritance (Child extends Father, Mother) marked as not allowed.
Java inheritance types — solid arrow = extends, dashed arrow = implements
  • Single: one parent, one child — SmartPhone extends Mobile.
  • Multilevel: a chain — Son extends Father, Father extends GrandFather.
  • Hierarchical: one parent, many children — Manager, Developer, Tester extend Employee.
  • Multiple / hybrid: only through interfaces — class HybridCar extends Car implements Electric, Petrol.

Single inheritance

  • One child class extends exactly one parent class.
  • Real life: a basic mobile phone can make calls. A smartphone is a mobile phone that can also browse the internet. It inherits calling and adds browsing.
class Mobile {
    String brand;

    Mobile(String brand) {
        this.brand = brand;
    }

    void call(String number) {
        System.out.println(brand + " calling " + number);
    }
}

class SmartPhone extends Mobile {       // single: one parent
    SmartPhone(String brand) {
        super(brand);
    }

    void browse(String site) {
        System.out.println(brand + " opening " + site);
    }
}

public class SingleDemo {
    public static void main(String[] args) {
        SmartPhone p = new SmartPhone("Pixel");
        p.call("9876543210");          // inherited from Mobile
        p.browse("learncodeguru.com"); // own method
    }
}

Multilevel inheritance

  • A chain of inheritance: C extends B, and B extends A. C gets the members of both B and A.
  • Real life: a grandfather owns a house, the father buys a car, and the son buys a laptop. The son can use the house, the car, and his laptop.
  • Keep chains short (two or three levels). Deep chains are hard to understand and change.
class GrandFather {
    void house() {
        System.out.println("House from GrandFather");
    }
}

class Father extends GrandFather {      // level 2
    void car() {
        System.out.println("Car from Father");
    }
}

class Son extends Father {              // level 3
    void laptop() {
        System.out.println("Son buys his own laptop");
    }
}

public class MultilevelDemo {
    public static void main(String[] args) {
        Son s = new Son();
        s.house();  // from GrandFather (two levels up)
        s.car();    // from Father
        s.laptop(); // own method
    }
}

Hierarchical inheritance

  • Many child classes extend the same parent class.
  • Real life: in a company, a manager, a developer, and a tester are all employees. They share a name, a salary, and a work method, but each has a special job.
  • This is the most common type in real projects: one base class with several specialisations.
class Employee {
    String name;

    Employee(String name) {
        this.name = name;
    }

    void work() {
        System.out.println(name + " is working");
    }
}

class Manager extends Employee {
    Manager(String name) { super(name); }
    void conductMeeting() { System.out.println(name + " conducts a meeting"); }
}

class Developer extends Employee {
    Developer(String name) { super(name); }
    void writeCode() { System.out.println(name + " writes Java code"); }
}

class Tester extends Employee {
    Tester(String name) { super(name); }
    void testApp() { System.out.println(name + " tests the app"); }
}

public class HierarchicalDemo {
    public static void main(String[] args) {
        Manager m = new Manager("Asha");
        Developer d = new Developer("Ravi");
        Tester t = new Tester("Kiran");
        m.work(); m.conductMeeting();
        d.work(); d.writeCode();
        t.work(); t.testApp();
    }
}

Multiple inheritance (through interfaces)

  • One class gets features from more than one parent type.
  • Java does not allow class C extends A, B. Instead a class can implements many interfaces.
  • Real life: a smartphone is a camera, a music player, and a phone at the same time.
  • The object can be used through any of those types: Camera c = phone;.
interface Camera {
    void takePhoto();
}

interface MusicPlayer {
    void playMusic(String song);
}

interface Phone {
    void call(String number);
}

class SmartPhone implements Camera, MusicPlayer, Phone { // multiple
    public void takePhoto() { System.out.println("Photo clicked"); }
    public void playMusic(String song) { System.out.println("Playing " + song); }
    public void call(String number) { System.out.println("Calling " + number); }
}

public class MultipleDemo {
    public static void main(String[] args) {
        SmartPhone s = new SmartPhone();
        s.takePhoto();
        s.playMusic("Vande Mataram");
        s.call("100");

        Camera c = s;       // a SmartPhone IS-A Camera
        MusicPlayer mp = s; // and IS-A MusicPlayer
        c.takePhoto();
        mp.playMusic("Jana Gana Mana");
    }
}

Why not multiple inheritance with classes? The diamond problem

  • If a child could extend two classes that both have skill(), which one should child.skill() run? This ambiguity is called the diamond problem.
  • Real life: if the father teaches driving and the mother teaches cooking, and both call it "my skill", a single "skill" request is unclear.
  • Java avoids it for classes. With interfaces, if two default methods clash, the class must override the method and choose explicitly with InterfaceName.super.method().
class Father {
    void skill() { System.out.println("Driving"); }
}

class Mother {
    void skill() { System.out.println("Cooking"); }
}

// class Child extends Father, Mother { }  // ERROR: a class can extend only one class

interface Singer {
    default void perform() { System.out.println("Singing"); }
}

interface Dancer {
    default void perform() { System.out.println("Dancing"); }
}

class Artist implements Singer, Dancer {
    @Override
    public void perform() {      // must resolve the clash
        Singer.super.perform();
        Dancer.super.perform();
    }
}

public class DiamondDemo {
    public static void main(String[] args) {
        new Artist().perform(); // Singing, then Dancing
    }
}

Hybrid inheritance

  • A combination of two or more types, for example single plus multilevel plus multiple.
  • With classes only, hybrid forms that need two parents are impossible, so Java builds them with one class parent plus interfaces.
  • Real life: a hybrid car is a car (which is a vehicle), and it can run on both electricity and petrol.
class Vehicle {
    void start() { System.out.println("Vehicle started"); }
}

class Car extends Vehicle {                                // single
    void openBoot() { System.out.println("Boot opened"); }
}

class Bike extends Vehicle { }                             // hierarchical: Vehicle has two children

interface Electric {
    default void charge() { System.out.println("Charging battery"); }
}

interface Petrol {
    default void refuel() { System.out.println("Filling petrol"); }
}

class HybridCar extends Car implements Electric, Petrol {  // multilevel + multiple
    void mode() { System.out.println("Switching between battery and petrol"); }
}

public class HybridDemo {
    public static void main(String[] args) {
        HybridCar h = new HybridCar();
        h.start();    // from Vehicle
        h.openBoot(); // from Car
        h.charge();   // from Electric
        h.refuel();   // from Petrol
        h.mode();     // own method
        new Bike().start();
    }
}

Visibility modes in Java: what the child class can access

  • C++ has three visibility modes for inheritance (public, protected, private). Java has only one: extends always works like C++ public inheritance.
  • So in Java, what a child can see depends only on the access modifier of each parent member.
  • Private parent fields still exist inside the child object; the child just cannot touch them directly. Use public or protected getters and setters.
  • Protected members are visible in the same package and in subclasses in other packages (through inheritance).
Parent memberSame classChild in same packageChild in different packageNon-child in same packageNon-child in different package
privateYesNoNoNoNo
default (no modifier)YesYesNoYesNo
protectedYesYesYes (through inheritance)YesNo
publicYesYesYesYesYes
// File: com/lcg/bank/Account.java
package com.lcg.bank;

public class Account {
    private double balance = 1000;         // only inside Account
    String branch = "Hyderabad";           // default: package com.lcg.bank only
    protected String holder = "Asha";      // package + subclasses anywhere
    public String bankName = "LCG Bank";   // everyone

    protected double getBalance() {
        return balance;
    }
}

// File: com/lcg/loans/HomeLoanAccount.java  (different package)
package com.lcg.loans;

import com.lcg.bank.Account;

public class HomeLoanAccount extends Account {
    void show() {
        System.out.println(bankName);      // OK: public
        System.out.println(holder);        // OK: protected, through inheritance
        System.out.println(getBalance());  // OK: protected method
        // System.out.println(branch);     // ERROR: default access, other package
        // System.out.println(balance);    // ERROR: private
    }
}

Visibility modes: C++ vs Java

  • If you know C++, this table shows how its three visibility modes map to Java.
PointC++ public modeC++ protected modeC++ private modeJava extends
Syntaxclass B : public Aclass B : protected Aclass B : private Aclass B extends A
Parent public member becomespublicprotectedprivatepublic (unchanged)
Parent protected member becomesprotectedprotectedprivateprotected (unchanged)
Parent private memberNot accessibleNot accessibleNot accessibleNot accessible
Outside code sees B IS-A A?YesNoNoYes, always
Java equivalentextendsNo direct equivalentComposition: a private field of type AThe only mode

Access rules when overriding a method

  • An overriding method can keep or widen the access level, but never make it narrower.
  • Reason: code that works with the parent type must still be able to call the method on any child object.
  • The return type may be the same or a subtype (covariant return). Checked exceptions may be fewer or narrower, never broader.
Parent method accessAllowed in the child overrideNot allowed
publicpublic onlyprotected, default, private
protectedprotected, publicdefault, private
default (no modifier)default, protected, public (child in same package)private
privateNot inherited, so a same-name child method is a new method, not an override@Override on it is a compile error
class Parent {
    protected void show() {
        System.out.println("Parent show");
    }
}

class Child extends Parent {
    @Override
    public void show() {                 // OK: protected -> public (wider)
        System.out.println("Child show");
    }
    // @Override
    // void show() { }                   // ERROR: attempting to assign weaker access privileges
}

public class OverrideAccess {
    public static void main(String[] args) {
        Parent p = new Child();
        p.show(); // Child show
    }
}

The super keyword in inheritance

UseSyntaxPurpose
Call parent constructorsuper(args);Initialize the parent part of the object. Must be the first statement in the constructor.
Call parent methodsuper.method();Reuse the parent logic inside an override, then add more
Access parent fieldsuper.fieldRead a parent field hidden by a child field with the same name
class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    void introduce() {
        System.out.println("I am " + name);
    }
}

class Student extends Person {
    String name = "child field"; // hides Person.name (avoid in real code)
    int rollNo;

    Student(String name, int rollNo) {
        super(name);               // 1. parent constructor
        this.rollNo = rollNo;
    }

    @Override
    void introduce() {
        super.introduce();         // 2. parent method
        System.out.println("My roll number is " + rollNo);
        System.out.println(super.name + " / " + name); // 3. parent field vs child field
    }

    public static void main(String[] args) {
        new Student("Asha", 21).introduce();
    }
}
// Output:
// I am Asha
// My roll number is 21
// Asha / child field

Constructor chaining in inheritance

  • Constructors are not inherited. Every child constructor calls a parent constructor first, either explicitly with super(...) or implicitly with super().
  • So constructors run from the top of the hierarchy down: Object, then the grandparent, then the parent, then the child.
  • If the parent has only a parameterized constructor, the child must call super(args) explicitly, otherwise it is a compile error.
class Vehicle {
    Vehicle(String type) {
        System.out.println("1. Vehicle: " + type);
    }
}

class Car extends Vehicle {
    Car(String model) {
        super("four-wheeler");           // required: Vehicle has no no-arg constructor
        System.out.println("2. Car: " + model);
    }
}

class ElectricCar extends Car {
    ElectricCar(String model, int rangeKm) {
        super(model);
        System.out.println("3. ElectricCar range: " + rangeKm + " km");
    }
}

public class ChainDemo {
    public static void main(String[] args) {
        new ElectricCar("Nexon EV", 465);
    }
}
// Output:
// 1. Vehicle: four-wheeler
// 2. Car: Nexon EV
// 3. ElectricCar range: 465 km

What is inherited and what is not

Parent memberInherited?Notes
public and protected fields and methodsYesUsable directly in the child
Default (package) membersOnly if the child is in the same packageInvisible to children in other packages
private fields and methodsNot accessibleFields still exist in the object; use getters and setters
ConstructorsNoCalled with super(...)
static membersAccessibleStatic methods are hidden, not overridden
final methodsYesCannot be overridden
Static and instance initializer blocksNoThey run as part of creating the parent part
Nested classesYes, if accessibleFollow the same access rules

Differences between IS-A (inheritance) and HAS-A (composition)

PointIS-A (inheritance)HAS-A (composition)
MeaningChild is a kind of parentClass contains another object as a field
Keywordextends / implementsNo keyword, just a field
ExampleCar IS-A VehicleCar HAS-A Engine
CouplingTight: child depends on parent internalsLoose: depends only on the public API
Change at runtimeNo, fixed at compile timeYes, the field can hold a different object
Number allowedOne class parentAny number of fields
Use whenThe child truly is a specialised parentYou only want to reuse behaviour
class Engine {
    void start() { System.out.println("Engine started"); }
}

class Vehicle {
    void move() { System.out.println("Vehicle moving"); }
}

class Car extends Vehicle {               // Car IS-A Vehicle
    private final Engine engine = new Engine(); // Car HAS-A Engine

    void drive() {
        engine.start();
        move();
    }

    public static void main(String[] args) {
        new Car().drive();
    }
}
L2

Advanced — Inheritance

Method overriding and runtime polymorphism

  • A parent reference can point to any child object: Shape s = new Circle(1); (upcasting).
  • When an overridden method is called, the JVM picks the version from the actual object at runtime (dynamic method dispatch).
  • This lets one loop handle many types without if or switch on the type.
class Shape {
    double area() { return 0; }
}

class Circle extends Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    @Override double area() { return Math.PI * r * r; }
}

class Rectangle extends Shape {
    private final double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    @Override double area() { return w * h; }
}

public class PolyDemo {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Rectangle(2, 3), new Circle(2) };
        double total = 0;
        for (Shape s : shapes) {
            System.out.printf("%s area = %.2f%n", s.getClass().getSimpleName(), s.area());
            total += s.area();
        }
        System.out.printf("Total = %.2f%n", total);
    }
}

Upcasting, downcasting, and instanceof

  • Upcasting (child to parent) is automatic and always safe.
  • Downcasting (parent to child) needs an explicit cast and can throw ClassCastException if the object is not really that child.
  • Check first with instanceof. Since Java 16, pattern matching does the check and the cast together: if (a instanceof Dog d).
class Animal {
    void eat() { System.out.println("Animal eats"); }
}

class Dog extends Animal {
    @Override void eat() { System.out.println("Dog eats bones"); }
    void fetch() { System.out.println("Dog fetches the ball"); }
}

class Cat extends Animal { }

public class CastDemo {
    public static void main(String[] args) {
        Animal a = new Dog();      // upcasting: automatic
        a.eat();                   // Dog eats bones
        // a.fetch();              // ERROR: type Animal has no fetch()

        if (a instanceof Dog d) {  // Java 16+ pattern matching
            d.fetch();             // safe downcast
        }

        Animal c = new Cat();
        // Dog wrong = (Dog) c;    // compiles, but ClassCastException at runtime
        System.out.println(c instanceof Dog); // false
    }
}

The Object class: root of every hierarchy

  • If a class has no extends, the compiler makes it extend java.lang.Object.
  • So every object has these methods. Override toString, equals, and hashCode in value classes.
Object methodDefault behaviourUsually override?
toString()ClassName@hexHashCodeYes, for readable output
equals(Object)Same object (==)Yes, for value equality
hashCode()Identity-based numberYes, whenever equals is overridden
getClass()Runtime class of the objectNo (it is final)
clone()Protected shallow copy; needs CloneableRarely; prefer copy constructors
wait(), notify(), notifyAll()Thread coordination on the object monitorNo (they are final)
import java.util.Objects;

class Point {
    private final int x, y;

    Point(int x, int y) { this.x = x; this.y = y; }

    @Override
    public String toString() { return "Point(" + x + ", " + y + ")"; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.y;
    }

    @Override
    public int hashCode() { return Objects.hash(x, y); }
}

public class ObjectDemo {
    public static void main(String[] args) {
        Point a = new Point(2, 3);
        Point b = new Point(2, 3);
        System.out.println(a);                            // Point(2, 3)
        System.out.println(a == b);                       // false: different objects
        System.out.println(a.equals(b));                  // true: same values
        System.out.println(a.getClass().getSuperclass()); // class java.lang.Object
    }
}

Stopping inheritance: final and sealed classes

  • A final class cannot be extended (String, Integer). A final method cannot be overridden.
  • A sealed class or interface (Java 17) lists exactly which classes may extend it with permits.
  • With a sealed hierarchy, a Java 21 switch can cover every case without a default branch.
class Payment {
    final void audit() { System.out.println("Audit log written"); } // cannot be overridden
}

final class UpiPayment extends Payment { }   // nobody can extend UpiPayment
// class FastUpi extends UpiPayment { }      // ERROR: cannot inherit from final

sealed interface Shape permits Circle, Square { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }

public class SealedDemo {
    static double area(Shape s) {
        return switch (s) {                  // Java 21: exhaustive, no default needed
            case Circle c -> Math.PI * c.r() * c.r();
            case Square q -> q.side() * q.side();
        };
    }

    public static void main(String[] args) {
        System.out.println(area(new Square(4))); // 16.0
        new UpiPayment().audit();                // inherited final method
    }
}

Field hiding vs method overriding

  • Methods are polymorphic; fields are not. A child field with the same name hides the parent field.
  • Field access is decided by the reference type at compile time, while overridden methods are decided by the object at runtime.
  • Avoid same-name fields in parent and child. Keep fields private and use methods.
class Parent {
    String type = "Parent field";
    String describe() { return "Parent method"; }
}

class Child extends Parent {
    String type = "Child field";                   // hides, does not override
    @Override String describe() { return "Child method"; }
}

public class FieldHidingDemo {
    public static void main(String[] args) {
        Parent p = new Child();
        System.out.println(p.type);       // Parent field (reference type)
        System.out.println(p.describe()); // Child method (object type)
    }
}

Pitfall: calling overridable methods from a constructor

  • The parent constructor runs before the child fields are initialized.
  • If the parent constructor calls a method that the child overrides, the child version runs and sees default values like null or 0.
  • Rule: constructors should call only private, final, or static methods.
class Base {
    Base() {
        init(); // dangerous: runs the child version before child fields are set
    }

    void init() { System.out.println("Base init"); }
}

class Derived extends Base {
    private String name = "LCG";

    @Override
    void init() { System.out.println("Derived init, name = " + name); }
}

public class CtorPitfall {
    public static void main(String[] args) {
        new Derived(); // Derived init, name = null
    }
}

Composition over inheritance

  • Inheriting from a class exposes all its public methods, including ones that break your rules.
  • If the relationship is "uses" or "has", keep the other object as a private field and expose only what you need.
import java.util.ArrayList;
import java.util.List;

// BAD: class Playlist extends ArrayList<String>
//      exposes remove, clear, set, sort, and every other list method

class Playlist {                                   // GOOD: Playlist HAS-A list
    private final List<String> songs = new ArrayList<>();

    void add(String song) {
        if (!songs.contains(song)) songs.add(song); // our rule: no duplicates
    }

    int size() { return songs.size(); }

    List<String> view() { return List.copyOf(songs); }
}

public class CompositionDemo {
    public static void main(String[] args) {
        Playlist p = new Playlist();
        p.add("Song A");
        p.add("Song B");
        p.add("Song A");                                // ignored
        System.out.println(p.size() + " " + p.view());  // 2 [Song A, Song B]
    }
}
L3

Tricky Interview Points

Q1) What is inheritance in Java?

Answer A mechanism where a child class acquires the fields and methods of a parent class using extends, and can add or override behaviour. It models an IS-A relationship.

Q2) What are the types of inheritance in Java?

Answer Single, multilevel, and hierarchical with classes. Multiple and hybrid inheritance are achieved through interfaces.

Q3) Give a simple real-life example for each type of inheritance.

Answer Single: Mobile to SmartPhone. Multilevel: GrandFather to Father to Son. Hierarchical: Employee to Manager, Developer, Tester. Multiple: SmartPhone implements Camera, MusicPlayer, Phone. Hybrid: HybridCar extends Car (which extends Vehicle) and implements Electric and Petrol.

Q4) Does Java support multiple inheritance?

Answer Not with classes, to avoid the diamond problem. A class can implement many interfaces, which gives multiple inheritance of type and, since Java 8, of default method bodies with conflict rules.

Q5) What is the diamond problem and how does Java handle it with interfaces?

Answer It is the ambiguity when two parents provide the same method. With interfaces, if two default methods clash the class must override the method and can call the one it wants with InterfaceName.super.method().

Q6) Does Java have visibility modes like C++?

Answer No. C++ has public, protected, and private inheritance. Java extends always behaves like public inheritance, and what the child can access depends on the access modifier of each parent member.

Q7) Can a subclass access private members of the parent?

Answer Not directly. Private fields exist in the child object but are accessible only inside the parent class. Use protected or public getters and setters.

Q8) What is the difference between protected and default access in inheritance?

Answer Default members are visible only in the same package, even to subclasses. Protected members are visible in the same package and also to subclasses in other packages through inheritance.

Q9) Can we reduce the visibility of an overridden method?

Answer No. An override can keep or widen access, for example protected to public, but not narrow it. Narrowing is a compile error: attempting to assign weaker access privileges.

Q10) What is super()?

Answer A call to a parent constructor. If present it must be the first statement. If you do not write it, the compiler inserts super(), which fails if the parent has no no-arg constructor.

Q11) Are constructors inherited?

Answer No. Each class declares its own constructors, and every child constructor calls a parent constructor through super.

Q12) In what order do constructors run in multilevel inheritance?

Answer From the top down: Object, then the grandparent, then the parent, then the child, because each constructor first calls its parent constructor.

Q13) What is the difference between IS-A and HAS-A?

Answer IS-A is inheritance (Car is a Vehicle). HAS-A is composition (Car has an Engine). Prefer HAS-A unless the child truly is a specialised kind of the parent.

Q14) What does every class in Java extend?

Answer java.lang.Object, directly or indirectly, unless it is Object itself.

Q15) Can static methods be inherited and overridden?

Answer They are inherited (accessible through the child) but not overridden. A same-signature static method in the child hides the parent method.

Q16) How do you prevent a class from being inherited?

Answer Declare it final, or use a sealed class with permits to allow only specific subclasses. A private constructor also prevents subclassing from outside the class.

Q17) What is upcasting and downcasting?

Answer Upcasting assigns a child object to a parent reference and is automatic. Downcasting converts a parent reference back to a child type with an explicit cast and should be guarded with instanceof.

Q18) Are fields overridden like methods?

Answer No. Fields are hidden, not overridden. Field access uses the reference type, while overridden methods use the runtime object type.

Q19) Why should constructors not call overridable methods?

Answer Because the child override runs before the child fields are initialized, so it sees default values such as null or 0.

Q20) Why prefer composition over inheritance?

Answer Composition gives loose coupling, hides unwanted parent methods, and lets you change behaviour at runtime. Inheritance ties the child to the parent implementation.

L4

Simple Programs

Bank accounts (hierarchical + overriding)

class Account {
    protected final String holder;
    protected double balance;

    Account(String holder, double balance) {
        this.holder = holder;
        this.balance = balance;
    }

    boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    void print() {
        System.out.println(getClass().getSimpleName() + " " + holder + ": " + balance);
    }
}

class SavingsAccount extends Account {
    SavingsAccount(String holder, double balance) { super(holder, balance); }

    void addInterest(double ratePercent) {
        balance += balance * ratePercent / 100;
    }
}

class CurrentAccount extends Account {
    private final double overdraft;

    CurrentAccount(String holder, double balance, double overdraft) {
        super(holder, balance);
        this.overdraft = overdraft;
    }

    @Override
    boolean withdraw(double amount) {           // allows going below zero
        if (amount <= 0 || amount > balance + overdraft) return false;
        balance -= amount;
        return true;
    }
}

public class BankDemo {
    public static void main(String[] args) {
        SavingsAccount s = new SavingsAccount("Asha", 10000);
        CurrentAccount c = new CurrentAccount("Ravi", 5000, 2000);
        s.addInterest(5);
        System.out.println(s.withdraw(20000)); // false
        System.out.println(c.withdraw(6500));  // true (uses overdraft)
        s.print(); // SavingsAccount Asha: 10500.0
        c.print(); // CurrentAccount Ravi: -1500.0
    }
}

Employee salary using super.method()

class Employee {
    protected final String name;
    protected final double basic;

    Employee(String name, double basic) {
        this.name = name;
        this.basic = basic;
    }

    double salary() {
        return basic + basic * 0.20; // basic + 20% HRA
    }
}

class Manager extends Employee {
    private final double bonus;

    Manager(String name, double basic, double bonus) {
        super(name, basic);
        this.bonus = bonus;
    }

    @Override
    double salary() {
        return super.salary() + bonus; // reuse parent logic, then add
    }
}

public class SalaryDemo {
    public static void main(String[] args) {
        Employee[] staff = {
            new Employee("Kiran", 30000),
            new Manager("Asha", 50000, 15000)
        };
        for (Employee e : staff) {
            System.out.println(e.name + " = " + e.salary());
        }
        // Kiran = 36000.0
        // Asha = 75000.0
    }
}

Multilevel: toString chain with super.toString()

class Person {
    private final String name;
    Person(String name) { this.name = name; }

    @Override
    public String toString() { return "name=" + name; }
}

class Student extends Person {
    private final int rollNo;
    Student(String name, int rollNo) { super(name); this.rollNo = rollNo; }

    @Override
    public String toString() { return super.toString() + ", roll=" + rollNo; }
}

class GraduateStudent extends Student {
    private final String thesis;
    GraduateStudent(String name, int rollNo, String thesis) {
        super(name, rollNo);
        this.thesis = thesis;
    }

    @Override
    public String toString() { return super.toString() + ", thesis=" + thesis; }
}

public class ToStringChain {
    public static void main(String[] args) {
        System.out.println(new GraduateStudent("Asha", 7, "AI in Healthcare"));
        // name=Asha, roll=7, thesis=AI in Healthcare
    }
}

Vehicle rental (hierarchical + polymorphism)

class Vehicle {
    protected final String number;
    Vehicle(String number) { this.number = number; }

    int rentPerDay() { return 500; }

    int rent(int days) { return rentPerDay() * days; }
}

class Bike extends Vehicle {
    Bike(String number) { super(number); }
    @Override int rentPerDay() { return 300; }
}

class Car extends Vehicle {
    Car(String number) { super(number); }
    @Override int rentPerDay() { return 1500; }
}

class Truck extends Vehicle {
    Truck(String number) { super(number); }
    @Override int rentPerDay() { return 4000; }
}

public class RentalDemo {
    public static void main(String[] args) {
        Vehicle[] fleet = { new Bike("TS09AB1234"), new Car("TS10CD5678"), new Truck("TS11EF9012") };
        for (Vehicle v : fleet) {
            System.out.println(v.getClass().getSimpleName() + " " + v.number + " for 3 days = " + v.rent(3));
        }
    }
}

Hybrid: TeachingAssistant is a Student and a Teacher

class Person {
    protected final String name;
    Person(String name) { this.name = name; }
}

class Student extends Person {
    Student(String name) { super(name); }
    void attendClass() { System.out.println(name + " attends Java class"); }
}

interface Teacher {
    void teach(String topic);
}

interface Evaluator {
    default void grade() { System.out.println("Grading assignments"); }
}

class TeachingAssistant extends Student implements Teacher, Evaluator {
    TeachingAssistant(String name) { super(name); }

    @Override
    public void teach(String topic) {
        System.out.println(name + " teaches " + topic);
    }
}

public class HybridProgram {
    public static void main(String[] args) {
        TeachingAssistant ta = new TeachingAssistant("Ravi");
        ta.attendClass();      // from Student
        ta.teach("Arrays");    // implemented from Teacher
        ta.grade();            // default method from Evaluator
        Person p = ta;         // also IS-A Person
        System.out.println(p instanceof Teacher); // true
    }
}

Predict the output: fields, static, and instance methods

class A {
    String name = "A-field";
    static String who() { return "A-static"; }
    String show() { return "A-instance"; }
}

class B extends A {
    String name = "B-field";
    static String who() { return "B-static"; }
    @Override String show() { return "B-instance"; }
}

public class Predict {
    public static void main(String[] args) {
        A ref = new B();
        System.out.println(ref.name);   // A-field     (fields: reference type)
        System.out.println(ref.who());  // A-static    (static: reference type)
        System.out.println(ref.show()); // B-instance  (overridden: object type)
    }
}
L5

Problem Solving Tricks

  • Remember the five types with one family: single (parent to child), multilevel (grandfather to father to son), hierarchical (one parent, many children), multiple (two parents, only via interfaces), hybrid (a mix).
  • Java has no visibility modes: extends is always public-style. Parent access modifiers decide what the child sees.
  • Put @Override on every override so spelling and signature mistakes become compile errors.
  • Overrides may widen access but never narrow it: protected can become public, public can never become protected.
  • If the parent has no no-arg constructor, every child constructor must call super(args) first.
  • Fields and static methods use the reference type; overridden instance methods use the object type.
  • Keep hierarchies shallow, two or three levels. Deep trees are hard to change.
  • Use the IS-A test: if "Child is a Parent" sounds wrong, use composition (HAS-A) instead.
  • Mark classes final (or sealed) unless you designed them for extension.
  • Never call overridable methods from a constructor.
L6

Practice Programs List

  1. Single: create Mobile with call() and SmartPhone extends Mobile with browse(). Call both from a SmartPhone object.
  2. Multilevel: create GrandFather, Father, Son with one method each and call all three from a Son object.
  3. Hierarchical: create Shape with area() and three children Circle, Rectangle, Triangle. Print the areas in a loop.
  4. Multiple: create interfaces Printer and Scanner and a class AllInOnePrinter that implements both.
  5. Hybrid: create Vehicle -> Car -> HybridCar and make HybridCar implement Electric and Petrol.
  6. Write two default methods with the same name in two interfaces and resolve the clash using InterfaceName.super.method().
  7. Create a parent with private, default, protected, and public fields in one package and a child in another package. Note which lines compile.
  8. Fill a table of what a child can access for each modifier, then verify each cell with code.
  9. Try to override a public method with protected access and write down the exact compiler error.
  10. Give a parent class only a parameterized constructor and fix all child constructors using super(...).
  11. Print the constructor order of a three-level hierarchy with messages in each constructor.
  12. Override toString at three levels and build the full description using super.toString().
  13. Write a program where Parent p = new Child(); and print a hidden field, a static method, and an overridden method. Explain each result.
  14. Replace a bad class Playlist extends ArrayList<String> design with composition.