Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
Animal a = new Cat();
a.sound();
}
}
class Animal {
void sound() { System.out.print("..."); }
}
class Cat extends Animal {
@Override void sound() { System.out.print("Meow"); }
}Meow
- Expecting
...: the declared typeAnimalonly decides thatsoundmay be called; the version that runs is picked by the object, aCat. - Expecting
...Meow: an override replaces the parent's method; the parent's version runs only when the override callssuper.sound().
- What would the program print if
Catdid not overridesound? - Why does
a.purr()not compile whenCathas a methodpurr?