SyntaxPilot
Courses/Java/Lesson 18

Java · Lesson 18 of 51 · 11 min

Inheritance, super, method overriding

queued

These are the notes for Java episode 18. Episode 17 left us with a Teacher class that needed the same name, phone and phone check as Student, and we were about to copy-paste. Today we stop. You will see copy-pasted code drift apart, write the shared part once in a parent class with extends, use the is-a test, build objects with super(...) and see the order constructors run in, find out what child classes can't see, and let a child answer in its own way with method overriding and @Override. Every example was run with javac 21, with its real output or error.

The problem: two forms, one rule

The school office has a student admission form: name, phone, marks. For teachers they photocopy it and change one box. Later a rule is added ("phone must be 10 digits"), but only the student form is updated. One school, two rules.

class Student {
    String name;
    String phone;
    int marks;
    void setPhone(String phone) {
        if (phone.length() != 10) {
            System.out.println("Invalid phone: " + phone);
            return;
        }
        this.phone = phone;
    }
}

class Teacher {
    String name;
    String phone;
    String subject;
    void setPhone(String phone) {
        this.phone = phone;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.setPhone("12345");
        Teacher t = new Teacher();
        t.setPhone("12345");
        System.out.println("Teacher phone: " + t.phone);
    }
}
Invalid phone: 12345
Teacher phone: 12345

Why it went wrong

  • Name, phone and the phone check are shared by every person in the school, but we wrote them twice (and a Principal would make it three times).
  • A fix in one copy doesn't reach the others. Copies drift apart.
  • The cure: write the shared part once, and let Student and Teacher reuse it, each adding only what is really theirs.

extends: what children get from their parents

In a family In Java
Parents: surname, house, family rules Parent class (superclass): Person, the shared part written once
A child gets all of it at birth class Student extends Person: gets every field and method
Plus their own name and hobbies + int marks: the child adds only what's new

Inheritance means a class gets the fields and methods of another class. The keyword is extends. The class being extended is the parent class (also superclass or base class); the class that extends it is the child class (subclass or derived class).

class Person {
    String name;
    String phone;
    void setPhone(String phone) {
        if (phone.length() != 10) {
            System.out.println("Invalid phone: " + phone);
            return;
        }
        this.phone = phone;
    }
}

class Student extends Person {
    int marks;
}

class Teacher extends Person {
    String subject;
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.setPhone("12345");
        Teacher t = new Teacher();
        t.setPhone("12345");
        t.name = "Meena";
        t.subject = "Maths";
        System.out.println(t.name + " teaches " + t.subject);
    }
}
Invalid phone: 12345
Invalid phone: 12345
Meena teaches Maths
  • There is only one setPhone, so both classes follow the same rule.
  • Teacher never declared name: it was inherited from Person.
  • Change the rule in Person, and Student, Teacher and any future Principal get the fix at once.

The class diagram and the is-a test

            Person
        name, phone
        setPhone(String)
          ▲          ▲
   extends│          │extends
       Student     Teacher
       marks       subject

In UML class diagrams, a solid line with a hollow triangle pointing at the parent means "extends".

Before using extends, say it out loud: "a Student is a Person". True, so inheritance fits. "A Classroom is a Person"? False: a classroom has students, it isn't one. That's a different relationship (has-a: a field holding other objects). This check is called the is-a test.

super and constructors: the parent is built first

When Person gets a constructor that needs a name, Student's constructor must say how to build the Person part:

class Person {
    String name;
    Person(String name) {
        this.name = name;
        System.out.println("Person ready: " + name);
    }
}

class Student extends Person {
    int marks;
    Student(String name, int marks) {
        this.marks = marks;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Aarav", 95);
    }
}
Main.java:11: error: constructor Person in class Person cannot be applied to given types;
    Student(String name, int marks) {
                                    ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

A Student object contains a Person part, and that part must be built first, by a Person constructor. If you don't call one, Java silently inserts super() (no arguments), and Person has no such constructor.

super(...) calls the parent's constructor:

class Person {
    String name;
    Person(String name) {
        this.name = name;
        System.out.println("Person ready: " + name);
    }
}

class Student extends Person {
    int marks;
    Student(String name, int marks) {
        super(name);
        this.marks = marks;
        System.out.println("Student ready: " + marks);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Aarav", 95);
        System.out.println(s.name + " " + s.marks);
    }
}
Person ready: Aarav
Student ready: 95
Aarav 95

Rules:

  • The parent is always built before the child (foundation first, then the floors). With three levels A → B → C, new C() runs A's constructor, then B's, then C's.
  • super(...) must be the first statement of the constructor. Put it after this.marks = marks; and Java 21 says:
Main.java:12: error: call to super must be first statement in constructor
        super(name);
             ^
1 error
  • this(...) (episode 15) also has to be first, so a constructor can call this(...) or super(...), not both.
  • If the parent has a no-argument constructor, you may leave super() out; Java adds it.

private stays private, even from children

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

class Student extends Person {
    Student(String name) {
        super(name);
    }
    void hello() {
        System.out.println("Hi, " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        new Student("Aarav").hello();
    }
}
Main.java:13: error: name has private access in Person
        System.out.println("Hi, " + name);
                                    ^
1 error

The Student object does contain a name, but private means only Person's own code may touch it. Two fixes:

  1. Give Person a public String getName() and call it (usually the better choice: the parent keeps control).
  2. Mark the field protected (episode 17's "family recipe"): visible to child classes.

What a child class does not inherit: private members (they exist in the object but aren't accessible), and constructors (each class writes its own and calls super(...)).

Method overriding: the same question, a different answer

On the first day everyone is asked to introduce themselves. A visitor says "I am Meena"; a student says "I am Aarav, my roll number is 12". Same question, a different answer, like cooking your mum's recipe and adding your own twist.

Method overriding means a child class writes a method with the same name, parameters and return type as the parent's. For objects of the child class, the child's version runs.

class Person {
    String name;
    Person(String name) {
        this.name = name;
    }
    void introduce() {
        System.out.println("I am " + name);
    }
}

class Student extends Person {
    int roll;
    Student(String name, int roll) {
        super(name);
        this.roll = roll;
    }
    @Override
    void introduce() {
        super.introduce();
        System.out.println("My roll number is " + roll);
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person("Meena");
        p.introduce();
        Student s = new Student("Aarav", 12);
        s.introduce();
    }
}
I am Meena
I am Aarav
My roll number is 12
  • super.introduce() runs the parent's version (mum's recipe), then we add the twist. super. reaches the parent's method; super(...) calls the parent's constructor.
  • @Override is an annotation (a note to the compiler, starting with @): "this method is meant to override a parent method". It catches typos:
class Person {
    void introduce() {
        System.out.println("I am a person");
    }
}

class Student extends Person {
    @Override
    void introduse() {
        System.out.println("I am a student");
    }
}
Main.java:8: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

Without @Override, the typo compiles as a brand-new method that nobody calls. Always write it.

Overriding rules

Rule Real message when broken
Same name, same parameters, same (or a more specific) return type otherwise it's a different method (overloading), or a compile error
Can't make access weaker (e.g. parent public, child no keyword) error: introduce() in Student cannot override introduce() in Person / attempting to assign weaker access privileges; was public
A final method can't be overridden error: showId() in Student cannot override showId() in Person / overridden method is final
private and static methods aren't overridden a same-named method in the child is a separate method
One parent only: extends Person, Athlete error: '{' expected

Java allows only single inheritance of classes (one parent), so there's never confusion about which parent a method comes from. Interfaces (episode 21) solve the "more than one" need.

Every class without extends still has a parent: Object. That's where methods like toString() and equals() come from (episode 22).

Overloading vs overriding (so far)

Overloading (episode 11) Overriding
Where Same class Parent and child
Name Same Same
Parameters Different Same
Purpose One action, different inputs The child's own version of the parent's action

What you just invented

Problem Fix
The shared part copy-pasted into every class A parent class + extends
The parent part must be built with arguments super(...), first line, parent first
A child must answer in its own way Overriding, super.method(), @Override

That's inheritance.

The next problem: the school wants one list of everyone: Person[] people = { new Person("Meena"), new Student("Aarav", 12) };. When we loop and call introduce() on each, which version runs, Person's or Student's? Episode 19: polymorphism.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
No super(name) when Person needs a name error: constructor Person in class Person cannot be applied to given types; Java added super() but Person has no no-arg constructor super(name); as the first line
super(name) after other statements error: call to super must be first statement in constructor The parent is built first Move it to the top
Using a parent's private field error: name has private access in Person private: not even child classes getName(), or protected
Typo in an overriding method error: method does not override or implement a method from a supertype It became a new method Match the parent's name and parameters
Weaker access in an override attempting to assign weaker access privileges; was public A child can't hide what the parent made public Keep public
Overriding a final method overridden method is final final forbids overriding Don't override, or remove final in the parent
extends A, B error: '{' expected One parent class only Use interfaces (episode 21)

Mini project: school people

class Person {
    private String name;
    private String phone;
    Person(String name) {
        this.name = name;
    }
    String getName() {
        return name;
    }
    void setPhone(String phone) {
        if (phone.length() != 10) {
            System.out.println("Invalid phone for " + name + ": " + phone);
            return;
        }
        this.phone = phone;
    }
    void introduce() {
        System.out.println("I am " + name);
    }
}

class Student extends Person {
    private int roll;
    Student(String name, int roll) {
        super(name);
        this.roll = roll;
    }
    @Override
    void introduce() {
        super.introduce();
        System.out.println("  roll number " + roll);
    }
}

class Teacher extends Person {
    private String subject;
    Teacher(String name, String subject) {
        super(name);
        this.subject = subject;
    }
    @Override
    void introduce() {
        super.introduce();
        System.out.println("  I teach " + subject);
    }
}

class Principal extends Teacher {
    Principal(String name) {
        super(name, "Leadership");
    }
    @Override
    void introduce() {
        System.out.println("Good morning! I am Principal " + getName());
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Aarav", 12);
        Teacher t = new Teacher("Meena", "Maths");
        Principal p = new Principal("Dr. Rao");
        s.setPhone("98765");
        t.setPhone("9876543210");
        s.introduce();
        t.introduce();
        p.introduce();
    }
}
Invalid phone for Aarav: 98765
I am Aarav
  roll number 12
I am Meena
  I teach Maths
Good morning! I am Principal Dr. Rao

Principal extends Teacher, which extends Person: a three-level inheritance chain (multilevel inheritance).

Practice

  1. Predict the output, then run it:
class A {
    A() {
        System.out.println("A");
    }
}

class B extends A {
    B() {
        System.out.println("B");
    }
}

class C extends B {
    C() {
        System.out.println("C");
    }
}

public class Main {
    public static void main(String[] args) {
        new C();
    }
}
  1. Give Vehicle a constructor Vehicle(int wheels) and a method describe(). Write Bike and Car that extend it, call super(2) / super(4), and override describe() using super.describe().
  2. Which pairs pass the is-a test? Car → Vehicle, Engine → Car, Dog → Animal, Library → Book.
Solutions

1.

A
B
C

Each constructor implicitly calls super() first, so the oldest ancestor runs first.

2.

class Vehicle {
    int wheels;
    Vehicle(int wheels) {
        this.wheels = wheels;
    }
    void describe() {
        System.out.println("A vehicle with " + wheels + " wheels");
    }
}

class Bike extends Vehicle {
    Bike() {
        super(2);
    }
    @Override
    void describe() {
        super.describe();
        System.out.println("  and a kick-stand");
    }
}

class Car extends Vehicle {
    Car() {
        super(4);
    }
    @Override
    void describe() {
        super.describe();
        System.out.println("  and a boot");
    }
}

public class Main {
    public static void main(String[] args) {
        new Bike().describe();
        new Car().describe();
    }
}
A vehicle with 2 wheels
  and a kick-stand
A vehicle with 4 wheels
  and a boot

3. Car is a Vehicle (yes), Dog is an Animal (yes). An Engine is part of a Car and a Library has Books: has-a, not is-a, so use fields instead of extends.

Quick quiz

class Vehicle {
    Vehicle() {
        System.out.print("V ");
    }
    void horn() {
        System.out.print("beep ");
    }
}
class Bus extends Vehicle {
    Bus() {
        System.out.print("B ");
    }
    @Override
    void horn() {
        super.horn();
        System.out.print("POOO ");
    }
}
// in main:
new Bus().horn();

A) B V POOO B) V B beep POOO C) V B POOO D) B beep POOO

Answer

B. Building a Bus builds the Vehicle part first (V), then B. horn() is overridden in Bus and calls super.horn() first (beep), then POOO.

Interview questions

  1. What is inheritance? A mechanism where a class (child) acquires the fields and methods of another class (parent) using extends, so shared code is written once.
  2. Does Java support multiple inheritance? Not for classes (one parent only, avoiding the "diamond problem"). A class can implement many interfaces.
  3. What does super do? super(...) calls a parent constructor (first statement only); super.method() calls the parent's version of an overridden method; super.field reaches a parent field.
  4. In what order do constructors run? From the top of the hierarchy down: parent first, then child.
  5. Are constructors inherited? No. Each class has its own, and must call a parent constructor (explicitly or the implicit super()).
  6. Can you override a private, static or final method? No. Private methods aren't visible; static methods are hidden, not overridden; final methods forbid it.
  7. Why use @Override? The compiler checks that the method really overrides something, catching typos and signature mistakes.
  8. What is the is-a test? Inheritance fits only if "Child is a Parent" is true; otherwise use composition (has-a).

Glossary

Term Meaning Example
Inheritance A class gets the fields and methods of another class Student gets name from Person
extends The keyword that makes one class inherit from another class Student extends Person
Parent class / superclass / base class The class being inherited from Person
Child class / subclass / derived class The class that inherits Student
Is-a test "Child is a Parent" must be true for inheritance a Student is a Person
Has-a relationship One object contains another as a field (composition) a Car has an Engine
super(...) Calls the parent's constructor; must be the first statement super(name);
super.method() Calls the parent's version of a method super.introduce();
Implicit super() The no-argument parent constructor call Java adds if you write none
Method overriding A child class redefines a parent method with the same signature introduce() in Student
Method signature A method's name plus its parameter types introduce(), setPhone(String)
Annotation A note to the compiler starting with @ @Override
@Override Asks the compiler to check that a method really overrides one
Single inheritance A class can extend only one class
Multilevel inheritance A chain: Principal → Teacher → Person
Object The parent of every class that has no extends toString(), equals()

Summary

  • Copy-pasted code drifts apart; write the shared part once in a parent class.
  • class Student extends Person: the child gets the parent's fields and methods and adds its own. Check the is-a test.
  • The parent is built first: super(...) must be the first line of the child's constructor, or Java inserts super().
  • private members stay private even from children: use getters or protected.
  • Overriding: same name and parameters in the child; super.method() reuses the parent's version; @Override catches mistakes.
  • One parent per class; no weaker access in overrides; final methods can't be overridden.
  • Next: one Person[] holding many kinds of people. Which introduce() runs? Episode 19: polymorphism.