In: Computer Science
Assume that Animal is a class that has method void info() that prints "I am an animal". Classes Bird and Reptile both extend class Animal, and both override method info(). Class Bird implements method info to print "I am a bird", and class Reptile implements method info to print "I am a reptile ". Determine the outcome printed by the following lines of code.
Animal animal = new Animal();
animal.info(); //OUTCOME:
animal = new Reptile()
animal.info(); //OUTCOME:
animal = new Bird();
animal.info(); //OUTCOME:
class Animal {
public void info() {
System.out.println("I am an animal.");
}
}
class Bird extends Animal {
public void info() {
System.out.println("I am a bird.");
}
}
class Reptile extends Animal {
public void info() {
System.out.println("I am a reptile.");
}
}
class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.info();
animal = new Reptile();
animal.info();
animal = new Bird();
animal.info();
}
}
The implements keyword is used to implement an interface. The interface keyword is used to declare a special type of class that only contains abstract methods. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class.
Therefore,
The first two lines print "I am an animal" as the outcome.
The next two lines print "I am a reptile" as the outcome.
The last two lines print "I am a bird" as the outcome.
I have attached the output below: