Why does "beagle" use the "Dog" execution of speak() but uses the Animal classes legs variable (seems inconsistent)? And why do the constructors get run twice each if I only create 2 objects? (seen in output below)
This was an upcasting/downcasting example originally so I'm trying to change the type of the object aka Animal dog = new Dog(); instead of Dog dog = new Dog();
And in Animal dog = new Dog(), what does "Animal" represent and what does Dog() represent? (I believe one is the Object Type)
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class Animal {
int legs;
Animal(){
//this.legs = 5;
System.out.println("-- Animal Constructor called --");
}
void speak(){
System.out.println("Speak!");
}
}
class Dog extends Animal {
int legs;
Dog(){
this.legs = 4;
System.out.println("-- Dog Constructor called --");
}
void speak(){
System.out.println("Bow wow!");
}
}
class Main {
public static void main(String[] args) {
Animal beagle = new Dog();
Dog chew_wawa = new Dog();
// Animal animal = new Animal();
System.out.println(beagle.legs);
System.out.println(chew_wawa.legs);
// System.out.println(animal.legs);
beagle.speak();
chew_wawa.speak();
// animal.speak();
}
}
Why is the output for this code:
-- Animal Constructor called --
-- Dog Constructor called --
-- Animal Constructor called --
-- Dog Constructor called --
0
4
Bow wow!
Bow wow!
Process finished with exit code 0

When you create an object of a subclass (such as
Dog) and assign it to a superclass reference (such asAnimal), you are upcasting the object. Upcasting allows you to treat an object of a subclass as if it were an object of the superclass. In this case, when you call thespeak()method on the beagle object, it will use the implementation of thespeak()method in the Dog class, because that is the actual type of the object. However, when you access thelegsvariable of thebeagleobject, it will use the value of thelegsvariable defined in theAnimalclass, because that is the type of the reference variable.