문제

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 ?

도움이 되었습니까?

해결책

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).

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top