Machine-translated by Google. Questions are authored in English.
Top

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));
    }
}

  • A.The program prints dog true
  • B.The program prints dog false
  • C.The program prints animal false
  • D.The program prints animal true

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.