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