Understanding of object conversion in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.