-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$

closed as off-topic by Evil, Apass.Jack, chi, Andrej Bauer, Yuval Filmus Dec 30 '18 at 22:05

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – Evil, Apass.Jack, chi, Andrej Bauer, Yuval Filmus
If this question can be reworded to fit the rules in the help center, please edit the question.

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.

$\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.