How to call? How to do?
public class Test {
public static void main(String[] args) {
Test test = new Test();
Animal a = new Animal("Animal");
Dog d = new Dog(" BigDog ","yellow");
Cat c = new Cat(" SmallCat ","black");
test.f(a); test.f(d); test.f(c); //(1)
}
public void f(Animal a) {
System.out.println("name :"+ a.name);
if(a instanceof Dog) {
Dog dog = (Dog)a;
System.out.println(" "+ fursColor + "fur"); //!(2)!Error
}
else if(a instanceof Cat) {
Cat cat = (Cat)a;
System.out.println(" " + eyesColor + "eye"); //(3)!Error
}
}
}
Ask Question:
(1) What’s the meaning of this?
(2) How to call “yellow”?
(3) How to call “black”?
The method
fis usinginstanceofas it is not use polymorphic methods to select the right type.Can you be more specific as to what you don’t understand.
I assume you want is to retrieve the
Stringin the field indogwithdog.fieldNameNotShownInYourExampleas it did ina.nameto get the name.I assume it should be
"black"but its the same as 2)