This week's giveaway is in the Java/Jakarta EE forum. We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line! See
I am confused about what the output of this should be...my study guide shows:
I am guessing that Pony is called in the main method first (but how it returns Animal is beyond me). Then within the Pony class, the superclass constructor is called (Horse) and passed the string "black". Third, comes the string "animal" (from the Animal constructor of the Animal class). And lastly, the "new Horse" that was assigned the string "black".
I'm sure this is ALL totally wrong, but can someone please explain the order in which this is executed in the simplest terms possible. Also, what is the purpose of the Pony() constructor in the Pony class? and are all of these constructors implicitly declared as super?
Each constructor either calls another constructor from the same class (using this(...)) or a constructor from the super class. If you don't add a call to this(...) or super(...) yourself the compiler adds a call to super().
So let's investigate your code.
You create a Pony object. The constructor first calls the Horse(String) constructor. This in turn first calls the Animal() constructor because of the implicit super(). Therefore, "animal" is printed. The Horse(String) constructor now continues and prints the type, "black".
Next, the Pony constructor continues. This creates another Horse, so again the Animal() constructor is called (printing "animal") followed by the remainder of the Horse(String) constructor, and again the type ("black") is printed.
wow, this was a bit confusing. I do understand the use of the implicit super(). What I don't get is how do you know where to start calling these constructors? and this may be a dumb ?, but hey..that's why I'm here. IS THIS.. in the main method not used?
Also, is the Horse constructor that has the String parameter of "type" being overloaded with the other constructor's param of "black"?
Just trying to tear this thing apart to understand..thanks.
That line is used - everything starts in the main method.
- Line 18 creates a new Pony - that calls the Pony() constructor
- which calls the Horse(String) constructor
- etc, as Rob described
What's going on there isn't "overloading". Overloading refers to the case where you have more than one method with the same name, but with different argument types, which isn't happening here. What you do have is the Pony constructor calling the Horse constructor with the argument "black".