Java basic 12 type conversion and polymorphism (reprint)

Source: Internet
Author: User

Type check

Any of the variables and references in Java are declared in type declaration to be used. We've seen object data, class data, method parameters, method return values, and automatic variables inside methods, all of which need to declare their type. Java is a strongly typed (strongly typing) language that examines types. If we use the wrong type, it will cause an error.

For example, in the Test class below, we assign a cup class object to the Aperson class reference: public class test{
public static void Main (string[] args) {
Human Aperson;
Aperson = new Cup ();
}
Class human{
Public Human (int h) {
This.height = h;
}
public int getheight () {
return this.height;
}
public void growheight (int h) {
This.height = This.height + H;
}
private int height;
}
Class cup{
public void Addwater (int w) {
This.water = This.water + W;
}
public void Drinkwater (int w) {
This.water = this.water-w;
}
private int water = 0;
}
}
Javac will return:

Found:cup
Required:human
Aperson = new Cup ();
^
1 Error

Basic type conversion Java can type conversions of variables of a primitive type. Different basic types have different lengths and storage ranges. If we convert from a high-precision type to a low-precision type, such as converting from float to int, then we may lose information. Such conversions are called narrowing transformations (narrowing conversion). In this case, we need to display the declaration type conversions, for example: public class test{
public static void Main (string[] args) {
int A;
A = (int) 1.23;
System.out.println (a);
}
If we convert from a low-precision type to a high-precision type, there is no concern about loss of information. Such transformations are called Loose Transformations (widening conversion). We do not need to display the required type conversions, Java can be automated: public class test{
public static void Main (string[] args) {
int a = 3;
Double b;
b = A;
System.out.println (a);
}
}
Upcast and polymorphism

In Java, references can also be type-cast, but there are limitations.

We can convert a derived class reference to its base class reference, which is called an up conversion (upcast) or a loose conversion. The following Brokencup class inherits from the Cup class and overrides the Addwater () and Drinkwater () methods in the Cup class:

public class test{
public static void Main (string[] args) {
Cup Acup;
Brokencup Abrokencup = new Brokencup ();
Acup = Abrokencup;
Acup.addwater (10);
}
Class cup{
public void Addwater (int w) {
This.water = This.water + W;
}
public void Drinkwater (int w) {
This.water = this.water-w;
}
private int water = 0;
}
Class Brokencup extends cup{
public void Addwater (int w) {
System.out.println ("Shit,broken Cup");
}
public void Drinkwater (int w) {
System.out.println ("Om.. Nu..,no water Inside ");
}
}
}

Program Run Result:

Shit, broken Cup

As you can see above, no display instructions are required, and we refer to the base class referenced by Abrokencup to it by the derived class reference Acup. Type conversions will be done automatically by Java.

We then called the Addwater () method of the Acup (which we declared to be the cup type). Although Acup is a reference to the cup type, it actually calls the Brokencup Addwater () Method! That is, even if we pass the upcast and loose the referenced type to its base class, Java can still correctly recognize the type of the object itself and invoke the correct method. Java can identify the actual type of object according to the current situation, which is called polymorphism (polymorphism). Polymorphism is an important aspect of object-oriented.

Polymorphism is a mechanism supported by Java and an important concept of object-oriented. This raises a taxonomy of questions that both subclass objects are actually "yes" to the parent class object. For example, a bird, also an animal, a car, it must be a means of transport. Java tells us that a derived class object can be used as a base class object, and Java will handle the situation correctly.

We can say to drink water (Drinkwater) with cups (cup). In fact, the specific meaning of the action of drinking water will change greatly in the derived class. For example, using a straw to drink water, and drinking water from a broken cup, these two action differences will be very large, although we are in the abstract "drink water." We can, of course, program each derived class separately to invoke different Drinkwater methods. However, as programmers, we can program the cups, calling the Drinkwater () method of the cup, regardless of what kind of derivative cups the cup is. Java calls the appropriate method, as we saw in the program above.

Looking at a more meaningful example, we add a drink () method to the human class, which receives a cup object and an integer as a parameter. An integer indicates the amount of water to drink:

public class test{
public static void Main (string[] args) {
Human guest = new Human ();
Brokencup Hiscup = new Brokencup ();
Guest.drink (hiscup,10);
}
}
Class human{
void Drink (Cup acup,int W) {
Acup.drinkwater (w);
}
}

Program Run Result:

Shit, no water inside

In the definition of drink () of the human class, we require the first parameter to be a reference to the cup type. But when actually applied (test Class), the brokencup of the Cup is derived from the class object. This is actually the hiscup upward transformation called the Cup class, passed to the drink () method. In the method, we call the Drinkwater () method. Java discovers that this object is actually a Brokencup object, so the corresponding method of Brokencup is actually called.

Downcast

We can transform a base class reference downward (downcast) into a reference to a derived class, but require that the base class reference the object it is pointing to, already the derived class object to be downcast. For example, the above hiscup can be transformed upward into a cup class reference, and then down into the Brokencup class reference.

Object type

In Java, all classes actually have a common ancestor of inheritance, the object class. The object class provides methods such as ToString (). We can override these methods in our own class definitions.

We can write a program that operates on object objects, and we can pass any object to the program through Upcast.

Related Article

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.