instanceof its role is to determine whether an object is a class or interface type. Because the Java language polymorphism allows you to assign an instance of a subclass to a variable of a parent class, but in some cases you need to determine the original type of the variable, you can use the instanceof implementation at this point. The sample code is as follows:
/**
* Define Animal Parent class
*/
Class animal{
}
/**
* Define Animal Subclass Dog
*/
Class Dog extends animal{
public void F1 () {
System.out.println ("woof woof");
}
}
/**
* Define animal Subclass Cat
*/
Class Cat extends animal{
public void F2 () {
System.out.println ("Miao Miao");
}
}
/**
* Define test class tests
*/
public class test{
public static void Main (string[] args) {
Dog d = new Dog ();
Show (d);
Cat C = new Cat ();
Show (c);
}
Define the parameters of the Show method using polymorphic features to improve the flexibility of the parameters
public static void Show (Animal a) {
if (a instanceof Dog) {
Dog Dog = (Dog) A;
DOG.F1 ();
}else if (a instanceof Cat) {
Cat cat = (cat) A;
Cat.f2 ();
}
}
}