-1
$\begingroup$

I am trying to understand the purpose of using the instanceof operator as a way to properly downcast an object in java. I really hope someone can help. Below is more code:

public class Test {
    public static void main(String [] args) {
            Dog k = new Dog();
            Animal v = new Dog();
            if (v instanceof Dog){
                k = (Dog)v;

            k.getAnimalName(); // displays Parent Animal
            k.getDogName(); // displays Dog
    }
}

public class Dog extends Animal{
    public void getDogName(){
        System.out.println("Dog");
    }
}

public class Animal{
    public void getAnimalName(){
        System.out.println("Parent Animal");
    }
}
  1. Confused about how v is an instance of type Dog. Can someone please explain this?

  2. Confused about what was displayed in the method calls (referring to k.getAnimalName() and k.getDogName). Is the reason behind why k could call both methods is because the type of k is a subclass of Animal?

$\endgroup$
  • $\begingroup$ Welcome to Computer Science! It might be a surprise to you, but your question is off-topic here. We deal with computer science questions, not programming questions. Please see our help on topic. $\endgroup$ – John L. Dec 30 '18 at 16:58
  • $\begingroup$ Also posted on Stackoverflow. Please do not post the same question on multiple sites. Each community should have an honest shot at answering without anybody's time being wasted. If you don't get a satisfying answer after a week or so, you may flag to request migration. $\endgroup$ – John L. Dec 30 '18 at 16:58
1
$\begingroup$

new Dog() returns a reference to a Dog object.

Animal v = new Dog () creates a Dog object, and assigns a reference to the variable v. At this point the compiler forgets what kind of object v is a reference to (it is a reference to an Animal or a subclass), but the reference is a reference to a Dog object.

v instanceof Dog checks what the object really is. You could have assigned a reference to a Cat object, but you did assign the result of new Dog(), so v is actually a Dog object and v instanceof Dog returns true.

(Dog) v would fail if v wasn't really a Dog object, but it is a Dog object (even though it is only declared as an Animal), so the assignment is fine.

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you very much for explaining this clearly :) $\endgroup$ – Townsend Dec 30 '18 at 22:24
  • $\begingroup$ Is it correct to say that the variable v contains the reference to a Dog object AND the variable type for v is an Animal? I want to make sure that I am using the correct language. Also, what is the point of doing the casting of (Dog)v in the first place if we know that v is a Dog object prior to that line being called? (I'm referring to the line k = (Dog)v). $\endgroup$ – Townsend Dec 30 '18 at 22:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.