• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class extension error

 
Randy Smith
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings, appreciate if someone could explain why the answer is not option a?

Assuming these classes are in the appropriate files, what is the output of the following program?



a) A Test
b) A Test B Test
c) B Test <--answer
d) B Test A Test
e) an error occurs

 
Randy Smith
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Am I right to say that is because object is created as B, that's why constructor of B is called. appreciate if someone could explain what is going on for this statement



b is the reference but it is declared as Type A, created as instance of B? Now, instance B is type of B or A??
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The object is a B. It's then been assigned to a reference of type A (and you're allowed to do this because B extends A, which means a B IS-AN A), but the actual object is still a B. You can't change the type of an object once created, you can only assign it to different types of reference.

The other part to realise is that the B constructor will always call an A constructor. Since it doesn't to this explicitly (with a call to super(...)), it calls the no-arg constructor. And that's why the answer isn't (b). You can explore this example further to understand how constructors call each other:

- Add the line super(msg); at the beginning of the B constructor. Now the output will match (b).

- Comment out the no-arg constructor in A. No change, because the B constructor is calling the A constructor that takes a String.

- Remove the super() line you just added. Now it won't compile. With no call to super(), it'll try and call the no-arg constructor. But there isn't one!
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in B's constructor, a call to its no argument super constructor is inserted by the compiler. The reference b points to the instance of B.

Using an instanceof operator and checking b will return true for both B and A
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic