Java. Lang. classcastexception

Source: Internet
Author: User

Classcastexception, literally, is a type conversion error, which is usually an error during forced type conversion. Next, analyze the causes of classcastexception, and provide a solution to this exception.

How does this exception occur? Let's give a more vivid example.

Animal indicates animals, dog indicates dogs, cat indicates cats, and animal subclasses. See the followingCode:

Animal a1 = new dog (); // 1

Animal a2 = new CAT (); // 2

 

Dog d1 = (DOG) A1; // 3

Dog D2 = (DOG) A2; // 4

The Code in line 2 is basically the same as that in line 2. It literally converts an animal (animal) to a dog, but the code in line 3 produces a java. Lang. classcastexception. The reason is that you want to convert a cat (A2 this animal is a cat) into a dog, and In line 2, it is to convert the dog into a dog, so you can.

From the above example, Java. lang. classcastexception is an exception generated during forced type conversion. Forced type conversion is performed only when the type of the object to which the parent class references is a subclass, if the type of the object referenced by the parent class is not a subclass, Java is generated. lang. classcastexception exception. Both A1 and A2 are animals, but A1 is a dog, while A2 is a cat. Therefore, A1 must be converted into a dog, because A1 is a dog and A2 is a cat, an error occurs when it is converted to a dog.

How can this problem be solved? If you know the specific type of the object to be accessed, convert it to this type. If the type cannot be determined, you can use the following two methods (assuming the object is O ):

1. Use O. getclass (). getname () to obtain the specific type. You can use the output statement to output this type and then perform specific processing based on the type.

2. The if (O instanceof type) statement is used to determine the type of O.

 

 

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.