aspose file tools*
The moose likes Beginning Java and the fly likes class extension error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "class extension error" Watch "class extension error" New topic
Author

class extension error

Randy Smith
Ranch Hand

Joined: Mar 27, 2011
Posts: 44
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

Joined: Mar 27, 2011
Posts: 44
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

Joined: Apr 06, 2010
Posts: 4490
    
    8

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
Bartender

Joined: May 31, 2011
Posts: 1776
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: class extension error