Chapter 4.3: Inheritance

Chapter 4.3: Inheritance · Study Questions
extendssuper and the constructor chainOverridingprotected and finalis-a / has-atoStringequals and hashCode
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Inheritance Concepts

Question 1: Not Inherited

After class Cat extends Animal is written, which members of Animal are not inherited by Cat?

C: Constructors are not inherited; a subclass constructor calls the superclass one with super(...). private fields are part of the object but cannot be accessed directly from the subclass; they are reached through the superclass’s public/protected methods.

Step-by-Step Trace · Constructors and super

Question 2: Constructor Chain: this and super

new Taxi() triggers four constructors. In what order are the lines printed?

StackHeapTaxi()main()t?#1 Taxiwheels0brandnull

new first allocates a single object; all fields, including those from the superclasses, get default values.

StackHeapTaxi(String)m"Fiat"Taxi()main()t?#1 Taxiwheels0brandnull

The first line is this("Fiat"): another constructor of the same class. A constructor starts with either this(...) or super(...), not both.

StackHeapCar(String)brand"Fiat"Taxi(String)m"Fiat"Taxi()main()t?#1 Taxiwheels0brandnull

super(m) calls the constructor of the superclass Car; that immediately calls super(4).

StackHeapVehicle(int)wheels4Car(String)brand"Fiat"Taxi(String)m"Fiat"Taxi()main()t?#1 Taxiwheels4brandnull

Vehicle (after the implicit super() to Object() has finished) fills in its own field and prints the first line.

StackHeapCar(String)brand"Fiat"Taxi(String)m"Fiat"Taxi()main()t?#1 Taxiwheels4brand"Fiat"

The Car constructor resumes where it left off: brand is filled in and the message is printed.

StackHeapTaxi(String)m"Fiat"Taxi()main()t?#1 Taxiwheels4brand"Fiat"

The rest of the Taxi(String) body: Taxi Fiat.

StackHeapTaxi()main()t?#1 Taxiwheels4brand"Fiat"

Last, the first-called Taxi() finishes: Taxi. Constructors complete from the top of the hierarchy downward.

StackHeapmain()t#1 Taxiwheels4brand"Fiat"

t refers to the object; both fields came from superclasses by inheritance: 4 Fiat.

class Vehicle {
  int wheels;
  Vehicle(int wheels) {
    this.wheels = wheels;
    System.out.println("Vehicle " + wheels);
  }
}
class Car extends Vehicle {
  String brand;
  Car(String brand) {
    super(4);
    this.brand = brand;
    System.out.println("Car " + brand);
  }
}
class Taxi extends Car {
  Taxi() { this("Fiat"); System.out.println("Taxi"); }
  Taxi(String m) { super(m); System.out.println("Taxi " + m); }
}
// in main:
Taxi t = new Taxi();
System.out.println(t.wheels + " " + t.brand);

Spot the Bug · Constructors and super

Question 3: Missing super(...)

The code does not compile. What is the cause? Would adding super(name); below the line this.number = number; fix it? Write the correct constructor.

class Person {
  private String name;
  Person(String name) { this.name = name; }
}
class Student extends Person {
  private int number;
  Student(String name, int number) {
    this.number = number;
  }
}
Show answer
error: constructor Person in class Person
  cannot be applied to given types;
  required: String
  found:    no arguments

If a constructor does not start with super(...), the compiler silently inserts super();; Person has no no-argument constructor.

Moving it below does not help in Java 21: error: call to super must be first statement in constructor. (Java 25 allows this order; the correct constructor is still the one below.)

Student(String name, int number) {
  super(name);
  this.number = number;
}

Coding Question · Constructors and super

Question 4: toString with super

The class Person has private String name, a constructor Person(String name) and a toString() that returns "Person: " + name. Write the class Student that extends Person and has a field private int number: the constructor passes the name to the superclass; toString() appends " (number)" to the superclass’s text. What does Person p = new Student("Ece", 1203); System.out.println(p); print?

Show answer
class Student extends Person {
  private int number;
  Student(String name, int number) {
    super(name);
    this.number = number;
  }
  @Override
  public String toString() {
    return super.toString() + " (" + number + ")";
  }
}

Output: Person: Ece (1203). Because name is private, Student cannot access it directly; it leaves that to super(name) and super.toString(). Even though the variable has type Person, Student’s toString() runs.

Multiple Choice · Overriding

Question 5: equals with a Point Parameter

Which statement is true for this class?

class Point {
  int x;
  @Override
  public boolean equals(Point n) {
    return x == n.x;
  }
}

A: The signature in Object is equals(Object). equals(Point) has a different parameter list, so it is overloading, not overriding; @Override catches this: method does not override or implement a method from a supertype.

Multiple Choice · Overriding

Question 6: Narrowing Access

Shape has public void draw(). What happens if void draw() { } (no modifier) is written inside Square extends Shape?

D: attempting to assign weaker access privileges; was public. Every reference of the superclass type must be able to call draw(); a subclass cannot break that promise. Access may stay the same or become wider.

Output Question · Overriding

Question 7: name() Inside super.show()

B overrides both name() and show(); show() calls super.show(). What does the program print?

class A {
  String name() { return "A"; }
  void show() {
    System.out.println("A:" + name());
  }
}
class B extends A {
  @Override String name() { return "B"; }
  @Override void show() {
    System.out.println("B");
    super.show();
  }
}
// in main:
new B().show();
new A().show();
Show answer
B
A:B
A:A
  • super.show() runs the body of A’s show(), but the object is still a B.
  • The name() in that body is really this.name(), and the overridden version is chosen: "B".
  • new A().show() on a plain A object: A:A.

Multiple Choice · Access and Restriction

Question 8: Who Can See protected?

In the package animals, Animal has protected String name;. Inside pets.Cat extends Animal there is return name;, and inside other.Keeper, which is not a subclass, there is return a.name;. Which statement is true?

B: protected = the class itself + the same package + subclasses. Cat is in another package but is a subclass. Keeper is neither in the same package nor a subclass: name has protected access in Animal.

Multiple Choice · Access and Restriction

Question 9: Restricting with final

How many compile errors does this code have?

class Animal {
  public final void breathe() { }
}
class Cat extends Animal {
  public void breathe() { }
}
final class Fixed { }
class Test extends Fixed { }

C: A final method cannot be overridden (overridden method is final); a subclass cannot be derived from a final class (cannot inherit from final Fixed). String, Math and Integer are also final classes.

Spot the Bug · Access and Restriction

Question 10: An Object with a Restricted View

Which line does not compile, and why? Fix the line so that it prints the result of isWinter() when the object is a Tire.

class Part {
  String serial;
  Part(String serial) { this.serial = serial; }
  String serialNo() { return serial; }
}
class Tire extends Part {
  boolean winter;
  Tire(String serial, boolean winter) {
    super(serial);
    this.winter = winter;
  }
  boolean isWinter() { return winter; }
}
// in main:
Part p = new Tire("XYZ-1", true);
System.out.println(p.serialNo());
System.out.println(p.isWinter());
Show answer
error: cannot find symbol
  symbol:   method isWinter()
  location: variable p of type Part

The type of the variable (Part) decides which methods can be called; even though the object is a Tire, Part has no isWinter(). p.serialNo() is valid: XYZ-1.

if (p instanceof Tire) {
  Tire l = (Tire) p;
  System.out.println(l.isWinter());
}

Output: XYZ-1, true.

Multiple Choice · Relationships Between Classes

Question 11: is-a or has-a?

In which pairing are both statements correct?

B: “Every student is a person” is true, so it is inheritance (is-a). A library has books, so it is composition (has-a): the books are held in a field. A car is not an engine, it has one; a Square is a Shape.

Output Question · The Object Class

Question 12: super.toString()

Bird does not override toString(). What does the program print?

class Animal {
  private String name;
  Animal(String name) { this.name = name; }
  @Override public String toString() {
    return "Animal[" + name + "]";
  }
}
class Cat extends Animal {
  private boolean pet;
  Cat(String name, boolean pet) {
    super(name); this.pet = pet;
  }
  @Override public String toString() {
    return super.toString() + ", pet=" + pet;
  }
}
class Bird extends Animal {
  Bird(String name) { super(name); }
}
// in main:
Animal a = new Cat("Tekir", true);
System.out.println("Record: " + a);
System.out.println(new Bird("Maviş"));
Show answer
Record: Animal[Tekir], pet=true
Animal[Maviş]
  • In the concatenation "Record: " + a, toString() is called automatically; since the object is a Cat, its version runs and starts with super.toString().
  • Bird has no toString(): the search moves one level up and finds Animal’s. Object’s version, of the form Bird@1b6d3586, is never reached.

Step-by-Step Trace · The Object Class

Question 13: Inside equals

On which line does equals finish in each call? What does the program print?

StackHeapmain()abc#1 Pointx1y2#2 Pointx1y2

Two separate objects with the same contents. c = a creates no new object: a and c refer to the same object.

StackHeapmain()abc#1 Pointx1y2#2 Pointx1y2

== compares references: #1 and #2 are different objects, so false.

StackHeapequals(Object o)thisodmain()abc#1 Pointx1y2#2 Pointx1y2

this = #1, o = #2. They are not the same object; o instanceof Point is true; through the downcast, d sees the same object as a Point.

StackHeapequals(Object o)thisodmain()abc#1 Pointx1y2#2 Pointx1y2

The fields are compared: 1 == 1 and 2 == 2, so true. Content equality.

StackHeapequals(Object o)thisomain()abc#1 Pointx1y2#2 Pointx1y2

a.equals(c): this == o is true; the fast path, true immediately.

StackHeapequals(Object o)thisomain()abc#1 Pointx1y2#2 Pointx1y2#3 Stringvalue"1,2"

o is a String: instanceof Point is false, so false. The cast is never reached, so no ClassCastException occurs.

class Point {
  int x, y;
  Point(int x, int y) { this.x = x; this.y = y; }
  @Override public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Point)) return false;
    Point d = (Point) o;
    return x == d.x && y == d.y;
  }
}
// in main:
Point a = new Point(1, 2), b = new Point(1, 2);
Point c = a;
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equals("1,2"));

Multiple Choice · The Object Class

Question 14: When hashCode Is Forgotten

Point overrides equals correctly but not hashCode. What does the program print?

HashSet<Point> set = new HashSet<>();
set.add(new Point(3, 4));
set.add(new Point(3, 4));
System.out.println(set.size() + " "
    + new Point(3, 4).equals(new Point(3, 4)));

A: HashSet first picks a bucket with hashCode, then compares only the elements in that bucket with equals. Object’s hashCode gives two separate objects (in practice) different values; equal points are never compared and are added twice. The compiler does not check this. Rule: if equals is overridden, hashCode must be too (e.g. Objects.hash(x, y)).

Multiple Choice · The Object Class

Question 15: null and instanceof

Cat extends Animal. For Animal a1 = new Cat(); Animal a2 = null;, what are a1 instanceof Animal, a1 instanceof Object and a2 instanceof Animal, in that order?

D: A subclass object is also an instance of its superclasses; every object is an Object. null refers to no object, so instanceof always gives false. That is why an equals that uses instanceof needs no separate null check.

The End

Chapter 4.3: Inheritance: Study Questions
Lecture slides: Chapter 4.3: Inheritance · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.