1. A reference-type variable of a base class can "point to" its child class object
2. A reference to a base class does not have access to the newly added members (properties and methods) of its child class object
3. You can use the reference variable instanceof class name to determine whether the object that the reference variable "points to" belongs to the class or subclass of the class.
4. A subclass object can be used as an object of a base class to use called up Transformation (upcasting), which is called downward transformation (downcasting).
public class Testcasting {
public void F (Animal a) {
System.out.println ("Name:" + a.name);
if (a instanceof Dog) {
Dog d = (dog) A;
System.out.println ("Furcolor:" + d.furcolor);
}
}//If the passed parameter is an object of the animal class, only name is printed, and if the passed-in parameter is the subclass dog object, you also need to print the Furcolor
public static void Main (string[] args) {
Animal a=new Animal ("Animal");
Dog D=new Dog ("Carl", "Black");
System.out.println (d instanceof Animal); //true
System.out.println (a instanceof Dog);//false
System.out.println (a instanceof Animal);//true
Animal a1=new Dog ("Dog1", "white");
System.out.println ("A1.name:" +a1.name+ ", A1.furcolor:" +a1.furcolor);// error, base class object A1 cannot access the newly added members of the subclass Furcolor
Dog d1= (dog) a1;// can cast a base class object A1 to a subclass object D1
System.out.println ("D1.name:" +d1.name+ ", D1.furcolor:" +d1.furcolor);
Testcasting test=new testcasting ();
Test.f (a);//name:animal
TEST.F (d);//name:carl Furcolor:black
}
}
Class animal{
String name;
Public Animal (String name) {
This.name=name;
}
}
Class Dog extends animal{
String Furcolor;
Public Dog (String name,string furcolor) {
Super (name);
This.furcolor=furcolor;
}
}