Java basic 12 type conversion and Polymorphism

Source: Internet
Author: User

Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!

 

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 introducePolymorphism).

 

Type check

Java arbitrary variables and referencesType Declaration(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 =NewCup ();}} 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. This conversion is calledContraction Transformation(Narrowing conversion ). In this case, we need to display the Declaration type conversion, for example:

 
Public ClassTest {Public Static VoidMain (string [] ARGs ){IntA;= (Int1.23;//Narrowing ConversionSystem. Out. println ();}}

 

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 ClassTest {Public Static VoidMain (string [] ARGs ){IntA = 3;DoubleB; B=A;// Widening ConversionSystem. Out. println ();}}

 

Basic type conversion

 

Upcast and Polymorphism

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

We canConversion of a category class to its base class reference, This is calledUp 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 =NewBrokencup ();
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" );}}

ProgramRunning 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 calledPolymorphism(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 to downcast to be a class reference, but the base class reference is required to point to the objectIs the response Class Object of the target 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 haveCommon inheritance ancestor, That isObject 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

 

Welcome to continue reading the "Java quick tutorial" SeriesArticle

 

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.