Home Superclass super Keyword Overriding Object Class Access Modifiers

Week 7: Inheritance

Liang Chapter 11 — Superclasses & Subclasses, the super Keyword, Method Overriding, the Object Class, and Access Modifiers

Superclasses & Subclasses

Inheritance allows a new class (subclass) to reuse, extend, and modify the behavior of an existing class (superclass). The subclass inherits all public and protected members of the superclass. The keyword extends establishes this relationship. (Liang, Section 11.2)

The "is-a" Relationship

Inheritance models an is-a relationship. A Circle is a GeometricObject. A Dog is an Animal. Always ask: does the subclass pass the is-a test?

«superclass» GeometricObject color : String · filled : boolean generalization «subclass» Circle radius : double

Step 1 — Define the Superclass

public class GeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated; public GeometricObject() { dateCreated = new java.util.Date(); } public GeometricObject(String color, boolean filled) { dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } public String getColor() { return color; } public void setColor(String c) { color = c; } public boolean isFilled() { return filled; } public void setFilled(boolean f) { filled = f; } @Override public String toString() { return "color: " + color + " filled: " + filled; } }

Step 2 — Define the Subclass

public class Circle extends GeometricObject { private double radius; public Circle() { } public Circle(double radius) { this.radius = radius; } public Circle(double radius, String color, boolean filled) { super(color, filled); // calls GeometricObject(color, filled) this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double r) { radius = r; } public double getArea() { return radius * radius * Math.PI; } public double getPerimeter() { return 2 * radius * Math.PI; } @Override public String toString() { return super.toString() + " radius: " + radius; } }

Step 3 — Using the Subclass

Circle c = new Circle(5.0, "red", true); // Inherited from GeometricObject: System.out.println(c.getColor()); // red System.out.println(c.isFilled()); // true // Defined in Circle: System.out.println(c.getArea()); // 78.53... System.out.println(c); // color: red filled: true radius: 5.0

What is NOT Inherited

A subclass inherits all public and protected members. It does NOT inherit private fields directly — they are hidden. Constructors are also NOT inherited; the subclass must define its own.

Q1: What keyword is used to make one class inherit from another?
A) implements
B) extends
C) inherits
D) super
The extends keyword establishes the inheritance relationship: class Dog extends Animal. (Liang, Section 11.2)
Q2: A Circle extends GeometricObject. Which statement is true?
A) Circle inherits the private fields of GeometricObject directly
B) Circle inherits the public and protected methods of GeometricObject
C) GeometricObject is a Circle
D) Circle cannot add new fields
Subclasses inherit public and protected members. Private fields exist in the superclass but are hidden from the subclass — accessed only via inherited getters/setters. (Liang, Section 11.2)

Section Score

0 / 0

The super Keyword

The super keyword refers to the superclass. It has two uses: (1) super() to call a superclass constructor, and (2) super.method() to call a superclass method that has been overridden. (Liang, Section 11.3)

Calling the Superclass Constructor

public class Animal { private String name; public Animal(String name) { this.name = name; } public String getName() { return name; } } public class Dog extends Animal { private String breed; public Dog(String name, String breed) { super(name); // MUST be the first statement — calls Animal(name) this.breed = breed; } }

Rule: super() Must Be First

super() must be the very first statement in the subclass constructor. If you omit it, Java automatically inserts super() (the no-arg version) — which causes a compile error if the superclass has no no-arg constructor.

Calling an Overridden Superclass Method

public class Animal { public String toString() { return "Animal"; } } public class Dog extends Animal { private String breed; public Dog(String breed) { this.breed = breed; } @Override public String toString() { return super.toString() + " — Breed: " + breed; // Output: "Animal — Breed: Labrador" } }

Constructor Chain

When you create a Dog object, Java builds the chain from the top:

1 Object() root — runs first, implicit at top of every chain 2 Animal(name) called via super(name) inside Dog's constructor 3 Dog(name, breed) runs last — object fully initialized

Trace: What does this print?

class A { A() { System.out.println("A created"); } } class B extends A { B() { System.out.println("B created"); } } // In main: new B();

Hint: B() has no super() call, so Java inserts super() automatically — invoking A() first.

Q1: What happens if a subclass constructor does NOT call super()?
A) The superclass constructor is skipped entirely
B) Java automatically inserts super() as the first line
C) A runtime error occurs
D) The subclass constructor does not compile
Java always inserts an implicit super() call if none is specified. This causes a compile error only if the superclass doesn't have a no-arg constructor. (Liang, Section 11.3)
Q2: Where must super() appear in a constructor?
A) Anywhere inside the constructor body
B) After all field assignments
C) As the very first statement
D) At the end of the constructor
super() must be the first statement in the constructor body. Placing it elsewhere causes a compile error. (Liang, Section 11.3)

Section Score

0 / 0

Method Overriding

A subclass can provide its own implementation of a method that is already defined in the superclass. This is called method overriding. The overriding method must have the same signature (name + parameters) as the parent method. (Liang, Section 11.4)

Override Example

public class Animal { public String sound() { return "..."; } } public class Dog extends Animal { @Override // annotation — tells compiler to verify this is an override public String sound() { return "Woof"; // replaces Animal's version } } public class Cat extends Animal { @Override public String sound() { return "Meow"; } }

Override vs. Overload

FeatureOverridingOverloading
WhereSubclassSame class
SignatureIdentical (same name + params)Same name, different params
Return typeSame (or covariant subtype)Can differ
Resolved atRuntime (dynamic binding)Compile time
Annotation@OverrideNone needed

Rules for Overriding

Must-Follow Rules

1. Same method name and parameter list as the superclass method.

2. Return type must be the same or a covariant (subtype) return.

3. Access modifier cannot be more restrictive (e.g., cannot change public to private).

4. A static method cannot be overridden — it can only be hidden.

5. A final method cannot be overridden at all.

Common Mistake — Overload Instead of Override

class Animal { public void sound(String name) { ... } } class Dog extends Animal { public void sound() { ... } // OVERLOAD, not override! Different parameter! }

Use @Override always — the compiler will catch this mistake and show an error immediately.

Q1: What does @Override do?
A) Creates a new method in the superclass
B) Prevents the method from being inherited
C) Tells the compiler to verify that this method actually overrides a parent method
D) Makes the method run faster
@Override is an annotation that instructs the compiler to verify the method correctly overrides a parent method. If no matching parent method exists, it's a compile error — helping catch typos. (Liang, Section 11.4)
Q2: Can a subclass change a public method to private when overriding?
A) Yes, access can always change freely
B) No — the overriding method cannot be more restrictive
C) Only if the class is declared final
D) Yes, but only for static methods
Overriding methods cannot reduce visibility. If the parent method is public, the override must also be public. You can widen visibility (e.g., protectedpublic), but never narrow it. (Liang, Section 11.4)

Trace: What does this print?

class Shape { public String describe() { return "Shape"; } } class Square extends Shape { @Override public String describe() { return super.describe() + " - Square"; } } // In main: System.out.println(new Square().describe());

Section Score

0 / 0

The Object Class

Every class in Java implicitly extends java.lang.Object. If you write class Dog {}, Java reads it as class Dog extends Object {}. The Object class defines methods that all objects share. (Liang, Section 11.7)

Key Methods of the Object Class

MethodDefault BehaviorShould Override?
toString()Returns class name + hash code (e.g., Dog@3d4eac69)Yes — for readable output
equals(Object)Compares references (==)Yes — to compare content
hashCode()Returns memory-based integerYes — when overriding equals
getClass()Returns the runtime classNo (final)

Overriding toString()

public class Student { private String name; private int id; public Student(String name, int id) { this.name = name; this.id = id; } @Override public String toString() { return "Student[" + name + ", id=" + id + "]"; } } // In main: Student s = new Student("Alice", 1001); System.out.println(s); // Student[Alice, id=1001] — toString() called automatically

Overriding equals()

When toString() is Called Automatically

Java calls toString() automatically in: System.out.println(obj), string concatenation "Value: " + obj, and when printing arrays via Arrays.toString(arr).

Q1: What does the default equals() from Object compare?
A) The content (fields) of two objects
B) The references — whether both variables point to the same object
C) The names of the classes
D) The hash codes only
The default equals() from Object uses == — comparing references. Override it to compare fields (content equality). (Liang, Section 11.7)
Q2: You define class Car {}. Which class does Car implicitly extend?
A) java.lang.Class
B) Nothing — it's a standalone class
C) java.lang.Object
D) java.lang.Base
Every Java class implicitly extends java.lang.Object unless it already extends another class. This is why all objects have toString(), equals(), and hashCode(). (Liang, Section 11.7)

Section Score

0 / 0

Access Modifiers in Inheritance

Java has four levels of access control. In inheritance, protected is especially important — it allows subclass access while hiding from the outside world. (Liang, Section 11.12)

Access Modifier Summary

ModifierSame ClassSame PackageSubclassEverywhere
private
(default)
protected
public

protected in Practice

public class Vehicle { protected int speed; // subclass can access this directly private int engineCode; // subclass CANNOT access this directly protected void accelerate() { speed += 10; } } public class Car extends Vehicle { public void turboBoost() { speed += 50; // OK — speed is protected accelerate(); // OK — accelerate() is protected // engineCode++; // ERROR — private field not accessible } }

Best Practice

In most designs, use private fields with public getters/setters. Use protected when you intentionally want subclasses to have direct field access — but do this carefully. Avoid protected fields when a getter/setter would do the job. (Liang, Section 11.12)

Q1: A field declared protected in a superclass is accessible from which of these?
A) Only from within the superclass itself
B) From any class in any package
C) From the superclass, its subclasses, and classes in the same package
D) Only from subclasses, not the same package
protected = same class + same package + subclasses. It's one step wider than default (package-private) because it also crosses package boundaries for subclasses. (Liang, Section 11.12)
Q2: A subclass is in a different package from its superclass. Which modifiers allow the subclass to access a superclass member?
A) private and default
B) protected and public
C) default only
D) All four modifiers
Across packages, only protected (for subclasses) and public (for everyone) are accessible. private and default are invisible outside their package. (Liang, Section 11.12)

Section Score

0 / 0

Week 7 Contents

Superclasses & Subclasses super Keyword Method Overriding Object Class Access Modifiers