abstract public class Animal { abstract public void greeting(); } public class C
ID: 3719414 • Letter: A
Question
abstract public class Animal {
abstract public void greeting();
}
public class Cat extends Animal {
@Override
public void greeting() {
System.out.println("Meow!");
}
}
public class Dog extends Animal {
@Override
public void greeting() {
System.out.println("Woof!");
}
public void greeting(Dog another) {
System.out.println("Woooooooooof!");
}
}
public class BigDog extends Dog {
@Override
public void greeting() {
System.out.println("Woow!");
}
@Override
public void greeting(Dog another) {
System.out.println("Woooooowwwww!");
}
}
Explain the outputs (or error) for the following test program. Make sure to include what line th error is on, a discription, and if it is an output error or error. List all lines, the code is supposed to have errors, which you will be finding and describing.
1 public class TestAnimal {
2 public static void main(String[] args) {
3 // Using the subclasses
4 Cat cat1 = new Cat();
5 cat1.greeting();
6 Dog dog1 = new Dog();
7 dog1.greeting();
8 BigDog bigDog1 = new BigDog();
9 bigDog1.greeting();
10
11 // Using Polymorphism
12 Animal animal1 = new Cat();
13 animal1.greeting();
14 Animal animal2 = new Dog();
15 animal2.greeting();
16 Animal animal3 = new BigDog();
17 animal3.greeting();
18 Animal animal4 = new Animal();
19
20 // Downcast
21 Dog dog2 = (Dog)animal2;
22 BigDog bigDog2 = (BigDog)animal3;
23 Dog dog3 = (Dog)animal3;
24 Cat cat2 = (Cat)animal2;
25 dog3.greeting(dog2);
26 dog2.greeting(bigDog2);
27 bigDog2.greeting(dog2);
28 }
29 }
Explanation / Answer
There are two errors in the code of TestAnimal Class and remaining classes are error free. I added the explanation above the line of error.
public class TestAnimal {
public static void main(String[] args) {
// Using the subclasses
Cat cat1 = new Cat();
cat1.greeting();
Dog dog1 = new Dog();
dog1.greeting();
BigDog bigDog1 = new BigDog();
bigDog1.greeting();
// Using Polymorphism
Animal animal1 = new Cat();
animal1.greeting();
Animal animal2 = new Dog();
animal2.greeting();
Animal animal3 = new BigDog();
animal3.greeting();
// As the Animal class is abstract you cannot instantiate the object
Animal animal4 = new Animal();
// Downcast
Dog dog2 = (Dog)animal2;
BigDog bigDog2 = (BigDog)animal3;
Dog dog3 = (Dog)animal3;
// You cannot cast a parent class to children. The reverse is possible
Cat cat2 = (Cat)animal2;
dog3.greeting(dog2);
dog2.greeting(bigDog2);
bigDog2.greeting(dog2);
}
}
**Comment for any further queries.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.