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.
w.detect
x.detect
w.subbie
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.