It seems to me like there is an error on the answer key for this assignment. Should #2 be B) rather than D)? I have pasted the question and answer below:
Which of the following declaration statements can be used to instantiate a new Guitar object bass?
-
Instrument bass = new Guitar();
-
Guitar bass = new Guitar();
-
Trumpet bass = new Guitar();
-
I only.
-
II only.
-
III only.
-
I and II.
-
I, II, and III.
2 Likes
Hi Anthony,
Both of these instantiations will work:
- Instrument bass = new Guitar();
- Guitar bass = new Guitar();
The first one is OK because the Guitar class extends the Instrument class. Since a Guitar is-an Instrument, it is ok to declare you have an Instrument, and when you construct it it is a Guitar. In general if you have a sub class and a super class, you can have the declaration and the constructor match, which is what we are used to, and is what we see in #2. You can also have:
SuperClassName varName = new SubClassName(); //This works
But you CANNOT have:
SubClassName varName = new SuperClassName();//This does not work. because the constructor for the Super will not set up the instance variables the Sub needs.
This can be a tricky concept! Thanks for reaching out, please reply if you have other questions:)
-Lindsay
1 Like