Correct understanding of casting in Java)

Source: Internet
Author: User
A fascinating feature of Java is its support for Runtime polymorphism (polymophism), which saves a lot of trouble with maintenance types. You can use a reference of a parent class to point to a subclass and then call the subclass method at runtime. In this way, no matter how many sub-classes you have extended in the future or the sub-classes of sub-classes, you can keep the program running without changing any code. JVM will take care of everything at runtime. To illustrate this, see the following example:

Example 1:

Public class animal {
Public void move (){
System. Out. println ("Animal: Generic move ");
}
}

Public class horse extends animal {
Public void move (){
System. Out. println ("horse: Run ");
}
Public void jump (){
System. Out. println ("horse: Jump ");
}
}

Public class testanimals {
Public static void move (animal ){
A. Move ();
}

Public static void main (string [] ARGs ){
Animal [] animals = {new animal (), new horse (), new animal ()};
For (animal A: animals ){
Move ();
}
}
}

When we run useanimal, the result is as follows:
Animal: Generic move
Horse: Run

As mentioned above, one advantage of doing so is that we only need to define a move (animal a) method in useanimals to operate on all animal, regardless of the specific type. If we add a dog type to the animals array, we can call the move method as long as the dog class overrides the move method in animal.

Let's go back to the topic of type conversion. In the main method of useanimals. in Java, the concern of classes and their subclasses can be regarded as a tree, where the parent class is located and the subclass is located. As the name suggests, the top crop class is to crop a subclass as the parent class. The result is that the subclass will "lose" some Members, and only the Members that share the parent class can be used, more accurately, it is a common API.

For example, the Code cannot be compiled:

Animal animal = new horse (); // upcasting
Animal. Jump (); // compiler complains, it cannot see "Jump ()"

In Java, cropping up is always allowed. You do not need to specify the conversion type. It is obvious that it is always possible to convert a wide type into a narrow type! What corresponds to upcasting is downcasting. In the preceding example, horse defines a jump method. If we do know that we are processing a horse object and want to call its jump method, what should we do?

Take a look at the Code:

Public class testanimals {
Public static void move (animal ){
A. Move ();
}

Public static void main (string [] ARGs ){
Animal [] animals = {new animal (), new horse (), new animal ()};
For (animal A: animals ){
Move ();
If (A instanceof horse ){
Horse H = (Horse);
H. Jump ();
}
}
}
}

To achieve this goal, we must display and convert an animal reference to a horse reference, and we must know clearly that the object we want to convert is indeed a horse object, this is why instanceof is used. What if there is no instanceof judgment?

See the modified Code:
Public class testanimals {
Public static void move (animal ){
A. Move ();
}

Public static void main (string [] ARGs ){
Animal [] animals = {new animal (), new horse (), new animal ()};
For (animal A: animals ){
Move ();
Horse H = (Horse);
H. Jump ();
}
}
}
This code can (actually !!) After compilation, an error occurs during running:

Animal: Generic move
Exception in thread "Main" Java. Lang. classcastexception: COM. My. Animal cannot be cast to com. My. Horse
At com. My. testanimals. Main (testanimals. Java: 12)

Oop! You may complain why the compiler cannot find this error, because obviously, how can we convert a horse object into an animal object? Can't the compiler find the object in the array? In fact, the compiler allows you to do this:

Animal A = new animal ()
Horse H = (Horse);

This is because the compiler can only determine whether two objects are in a type tree and cannot detect their specific relationships. If you try to do this:

Animal A = new animal ()
Stirngs S = (string);

The compiler will prompt you that you cannot convert an animal type to a string type. However, when the type to be converted and the converted type are in the same type tree, the situation is different because it may be correct or wrong, everything can be found only when running. Let's take a look at the following code:
(Suppose horse has a subclass of flyablehorse)

Animal A = new flyablehorse ()
Horse H = (Horse);

The two lines of code can be compiled without errors during the runtime. Because a points to the flyablehorse subclass of horse, you can crop A flyablehorse object as a horse object. Remember, everything is running !!!

So we can summarize as follows:

When cropping up, everything is natural and safe. You don't need to do anything.
When cropping down, you must convert the type displayed and know that what you are doing is correct. The compiler will not help you correct errors. Everything is known only when running.

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.