11. Inheritance Constructors

Question: Why do you need to call the superclass constructor if there’s a perfectly good constructor in the subclass?

Example 1

public class M {
    public int detect = 0;
    public M() { detect = 1; }
}
public class N extends M {
    public int subbie = 2;
    public N(int n) { subbie = n; }
}

Setup

Use this code to answer the questions below.

    M w = new M();
    N x = new N(5);

Questions

Find each value or explain why it is an error to attempt.

  1. w.detect
  2. x.detect
  3. w.subbie
  4. x.subbie

Example 2

What would change if the constructor for MM takes in an int?

public class MM {
    public int detect = 0;
    public MM(int k) { detect = k; }
}
public class NN extends MM {
    public int subbie = 2;
    public NN(int n) { subbie = n; }
}

Think about modifying the setup code and questions from above as little as possible.

Last modified August 18, 2023: 2022-2023 End State (7352e87)