Java variable types can be converted or between objects.
If the subclass object is converted to the parent class object, it cannot be forced conversion because the subclass inherits the parent class object.
However, when the parent class object is converted to a subclass object (when and only when the parent class object is originally converted by the subclass by default), the parent class object can be forcibly converted.
Public class testobject {
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Animal A = new animal ();
DOG d = new dog ("yellow ");
D. Name = "bigyellow ";
System. Out. println (A. Print (d ));
}
}
Class animal {
String name;
Public void setname (string N ){
This. Name = N;
}
Public String getname (){
Return this. Name;
}
Public String print (animal ){
String result = "";
If (A instanceof dog ){
DOG d = (DOG);
Result = "name:" + A. Name + "\ n" + "furcolor:" + D. furcolor;
} Else if (a instanceof cat ){
Cat c = (CAT);
Result = "name:" + A. Name + "\ n" + "eyecolor:" + C. eyecolor;
} Else {
Result = "name:" + A. Name;
}
Return result;
}
}
Class cat extends animal {
String eyecolor;
Public void seteyecolor (string e ){
This. eyecolor = E;
}
Public String geteyecolor (){
Return this. eyecolor;
}
CAT (string e ){
This. seteyecolor (E );
}
}
Class dog extends animal {
String furcolor;
Public void setfurcolor (string f ){
This. furcolor = F;
}
Public String getfurcolor (){
Return this. furcolor;
}
Dog (string d ){
This. setfurcolor (d );
}
}
96 stack Software Programming Network, http://www.96dz.com, provide C language, C ++ programming, VC ++ programming, Java programming, C # programming, net programming, Linux programming, Web programming and other comprehensive technical information