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 Circleis aGeometricObject. A Dogis anAnimal. Always ask: does the subclass pass the is-a test?
Step 1 — Define the Superclass
public classGeometricObject {
privateString color = "white";
privateboolean filled;
private java.util.Date dateCreated;
publicGeometricObject() {
dateCreated = new java.util.Date();
}
publicGeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
publicStringgetColor() { return color; }
public voidsetColor(String c) { color = c; }
publicbooleanisFilled() { return filled; }
public voidsetFilled(boolean f) { filled = f; }
@Override
publicStringtoString() {
return"color: " + color + " filled: " + filled;
}
}
Circle c = newCircle(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 classAnimal {
privateString name;
publicAnimal(String name) {
this.name = name;
}
publicStringgetName() { return name; }
}
public classDogextendsAnimal {
privateString breed;
publicDog(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.
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 classAnimal {
publicStringsound() {
return"...";
}
}
public classDogextendsAnimal {
@Override // annotation — tells compiler to verify this is an overridepublicStringsound() {
return"Woof"; // replaces Animal's version
}
}
public classCatextendsAnimal {
@Override
publicStringsound() {
return"Meow";
}
}
Override vs. Overload
Feature
Overriding
Overloading
Where
Subclass
Same class
Signature
Identical (same name + params)
Same name, different params
Return type
Same (or covariant subtype)
Can differ
Resolved at
Runtime (dynamic binding)
Compile time
Annotation
@Override
None 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
classAnimal {
public voidsound(String name) { ... }
}
classDogextendsAnimal {
public voidsound() { ... } // 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., protected → public), but never narrow it. (Liang, Section 11.4)
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
Method
Default Behavior
Should 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 integer
Yes — when overriding equals
getClass()
Returns the runtime class
No (final)
Overriding toString()
public classStudent {
privateString name;
privateint id;
publicStudent(String name, int id) {
this.name = name;
this.id = id;
}
@Override
publicStringtoString() {
return"Student[" + name + ", id=" + id + "]";
}
}
// In main:
Student s = newStudent("Alice", 1001);
System.out.println(s); // Student[Alice, id=1001] — toString() called automatically
Overriding equals()
@Override
publicbooleanequals(Object obj) {
if (this == obj) return true; // same reference?if (!(obj instanceof Student)) return false;
Student other = (Student) obj; // downcastreturn this.id == other.id && this.name.equals(other.name);
}
// Usage:
Student a = newStudent("Alice", 1001);
Student b = newStudent("Alice", 1001);
System.out.println(a == b); // false — different objects
System.out.println(a.equals(b)); // true — same content
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
Modifier
Same Class
Same Package
Subclass
Everywhere
private
✅
❌
❌
❌
(default)
✅
✅
❌
❌
protected
✅
✅
✅
❌
public
✅
✅
✅
✅
protected in Practice
public classVehicle {
protectedint speed; // subclass can access this directlyprivateint engineCode; // subclass CANNOT access this directlyprotected voidaccelerate() { speed += 10; }
}
public classCarextendsVehicle {
public voidturboBoost() {
speed += 50; // OK — speed is protectedaccelerate(); // 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)