Java basic 12 type conversion and Polymorphism

Source: Internet
Author: User

Java basic 12 type conversion and Polymorphism
We used classes to create new types and used inheritance to facilitate the process of creating classes. I will go deep into the type in this lecture and introduce the concept of polymorphism. Type check

Any variables and references of Java can be used only after type declaration. We have seen object data, class data, method parameters, method return values, and automatic variables inside the method. They all need to declare their types. Java is a strongly typed (strongly typing) language that checks the type. If we use a wrong type, it will cause an error.

The type is invalid.

For example, in the following Test class, 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{       /**     * constructor     */    public Human(int h)    {        this.height = h;    }    /**     * accessor     */    public int getHeight()    {       return this.height;    }    /**     * mutator     */    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 convert the types of variables of the basic 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 float to int, we may lose information. Such a conversion is called a narrowing conversion ). In this case, we need to display the Declaration type conversion, for example:

public class Test{    public static void main(String[] args)    {        int a;        a = (int) 1.23;  // narrowing conversion        System.out.println(a);    }}

If we convert from low-precision type to high-precision type, there is no concern about information loss. Such a transformation is called a widening conversion ). We do not need to display the required type conversion, Java can automatically perform:

public class Test{    public static void main(String[] args)    {         int a = 3;        double b;        b = a;  // widening conversion        System.out.println(a);    }}

 

 

Upcast and Polymorphism

 

In Java, references can also be converted to types, but there are restrictions.


We can convert a category class reference to its base class reference, which is called up conversion (upcast) or loose conversion. The following BrokenCup class inherits from the Cup class and covers the original addWater () and drinkWater () Methods of the Cup class:

public class Test{    public static void main(String[] args)    {         Cup aCup;        BrokenCup aBrokenCup = new BrokenCup();        aCup = aBrokenCup; // upcast        aCup.addWater(10); // method binding    }}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...num..., no water inside");    }}

Program running result:

Shit, broken cup

As you can see above, there is no need for any display instructions. We will reference the aCup class that aBrokenCup has given to it. Type conversion is automatically performed by Java.

We then called the addWater () method of aCup (we declare it as the Cup type. Although aCup is a reference of the Cup type, it actually calls the addWater () method of BrokenCup! That is to say, even if we loosen the referenced type into its base class after upcast, Java can still correctly identify the type of the object and call the correct method. Java can identify the real type of an object based on the current situation, which is called 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 classification problem, that is, the subclass object is actually a "yes" parent class object. For example, a bird is also an animal. A car is also a means of transportation. Java tells us that a textbook class object can be used as a base class object, and Java will correctly handle this situation.

For example, the following inheritance relationship:


We can say that we use a Cup to drink water (drinkWater ). In fact, the specific meaning of drinking water will change greatly in the category. For example, drinking water through a straw is very different from drinking water from a broken cup, although we say "Drinking Water" in the abstract ". Of course, we can program each sequence class separately and call different drinkWater methods. However, as a programmer, we can program the Cup and call the drinkWater () method of the Cup, no matter what kind of cups the Cup is. Java will call the correct method, as we can see in the above program.

Let's look at a more meaningful example. We add a drink () method to the Human class. This method receives a cup object and an integer as the 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 running result:

Shit, no water inside

In the definition of drink () of the Human class, the first parameter must be a reference of the Cup type. But in actual use (Test class), the Cup's BrokenCup category object. In fact, hisCup's upward transformation is called the Cup class and passed to the drink () method. In the method, we call the drinkWater () method. Java finds 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 downcast into a category class reference, but the base class reference is required to point to the object, which is already the category class object to be downcast. For example, you can transform hisCup to a Cup class reference, and then to a BrokenCup class reference.

Object Type

In Java, all classes actually have a common inheritance ancestor, that is, the Object class. The Object class provides some methods, such as toString (). We can override these methods in our class definition.


Object: Ancestor

We can write a program that operates the Object, and then pass any Object to the program through upcast.

I will go deep into the Object class in the future.

(The implementation of polymorphism relies on RTTI. I will go deep in the future .)

Summary

Basic type conversion

Polymorphism

Downcast

Object


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.