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");
}
}
Confused about how v is an instance of type Dog. Can someone please explain this?
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?