U2L6 Extra Practice - Class Hierachies

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?

  1. Instrument bass = new Guitar();

  2. Guitar bass = new Guitar();

  3. Trumpet bass = new Guitar();

  4. I only.

  5. II only.

  6. III only.

  7. I and II.

  8. I, II, and III.

1 Like

Hi Anthony,
Both of these instantiations will work:

  1. Instrument bass = new Guitar();
  2. 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:)

1 Like