Discussion
What will be the output of the program?
import java.util.*;
public class Example65
{
static class Animal
{
public String toString() { return "animal"; }
}
static class Dog extends Animal
{
public String toString() { return "dog"; }
}
public static void main(String[] args)
{
List<Animal> pets = new ArrayList<Animal>();
pets.add(new Dog());
Animal first = pets.get(0);
System.out.println(first + " " + (first instanceof Dog));
}
}
Answer: A
The list is declared to hold Animal, but the object stored is a Dog and both toString and instanceof ask about the runtime type. The declared type of the variable governs which methods may be CALLED, never which implementation runs, so the output is dog and true.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development