1
class Animal
{

}

    class Dog extends Animal
    {

    }

    class main
    {
      public static void main(String args[])
    Animal g= new Dog();
    System.out.println(g instanceof Dog);      // 1st case

    System.out.println(g instanceof Animal);   // 2nd case

}

QUESTION: why the output is true in both cases ?

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
nr5
  • 4,228
  • 8
  • 42
  • 82

2 Answers2

5

Because the object that is referenced, at run-time, by local variable g is of type Dog (and thus also an Animal, because Dog extends Animal, though that's missing from your example).

Arnout Engelen
  • 6,709
  • 1
  • 25
  • 36
4

This is polymorphism in action. See here and here.

If you want to avoid this behaviour, use getClass() instead of instanceof. See my answer here for an example.

Community
  • 1
  • 1
Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
  • though your example does not show your usage, be wary anytime you use this kind of construct on a class hierarchy. If you find yourself consistently checking the type in an if statement, you might want to consider putting that behavior inside a method which can be implemented differentl for each subclass. – Matt Aug 14 '12 at 14:31