Java Polymorphism (i)

Source: Internet
Author: User

Multi-state is the third most characteristic of object-oriented after encapsulation and inheritance. Real things often reflect a variety of forms, such as students, students are a kind of people, then a specific classmate Zhang San is a student is also a person, that appears two forms.
Java, as an object-oriented language, can also describe the various forms of a thing. If the student class inherits the person class, a student object is both student and person. A student object can either be assigned a reference to a student type, or it can be assigned a reference to a person type.
The final polymorphic embodiment is that the parent class reference variable can point to the subclass object: The parent class type variable name = new subclass type ();
1, the premise of polymorphism is that there must be a parent class relationship or class to implement the interface relationship, otherwise the polymorphic can not be completed.
2. When a parent class referencing a variable that uses polymorphism, it calls the method after the subclass is overridden.
Ii. Three forms of polymorphism:
1. Format of general class polymorphism definition
Parent class Variable name = new subclass ();

    class Fu {}    class Zi extends Fu {} //类的多态使用Fu f = new Zi();

2. The format of the abstract class of polymorphic definitions

abstract class fu { public abstract void method (); class zi extends Fu {public void method () {System.out.println (" overriding parent abstract Method ");}} //-class polymorphism using FU fu= new Zi ();       

3, interface polymorphism-defined format

 Interface fu {public abstract void method (); class zi implements Fu {public void method () {System.out.println (" overriding interface Abstract Method ");}} //interface polymorphism using fu fu = new Zi ();      

Note: Methods of the same parent class are overridden by different subclasses. The method that is called when the method is called is overridden for each subclass.

new Student();   Person p2 = new Teacher();   p1.work(); //p1会调用Student类中重写的work方法   p2.work(); //p2会调用Teacher类中重写的work方法

Thirdly, after mastering the basic use of polymorphism, what happens to the members of the class after polymorphism? In the previous study of inheritance, we know that the member variables between the child parent classes have their own specific changes, then when the polymorphism occurs, the member variables in the use of the change?
Polymorphic occurrences can cause a slight change in the member variables in the child's parent class. Look at the following code:

class fu {int num = 4; There's no such thing as a compile failure}class zi extends fu {int num = 5;} class demo { public static void Main (String[] args) {Fu f = new Zi (); System.out.println (F.num); Zi z = new Zi (); System.out.println (Z.num); }}  

Printed results: 4
5
Summary: When a member variable of the same name appears in the child parent class, when the variable is called by polymorphic:
1. Compile time: Refer to whether the referenced variable belongs to a class in which the member variable is called. No, compilation failed.
2. Runtime: It is also a member variable in the class to which the reference variable belongs.
Simple: Compile and run all refer to the left side of the equals sign. Compile run look to the left.

Polymorphic occurrences cause a slight change in the member methods in the child's parent class, as seen in the code:

ClassFu {int num =4;Without this method, the compilation failsvoid Show () {System.out.println ("Fu show num"); }}class zi extends Fu {int num = 5; //overriding the parent class method void Show () {System.out.println (" Zi show num "); } void show_1{System.out.println ( "Zi show Show_1");}} class demo { public static void Main (String[] args) {Fu f = new Zi (); F.show (); //f.show_1 ()}}            

Print result: Zi show num
Summary: Polymorphic member methods
1. Compile time: Refer to the class that the reference variable belongs to, if there is no method called in the class, the compilation fails (if the comment before F.show_1 () is opened, the compilation fails).
2. Runtime: Refer to the class to which the object refers to the reference variable, and run the member method in the class to which the object belongs (if the show () method overridden by the class is commented out, the result of printing is FU show num).
In short: Compile to look to the left and run to the right.

Four, the transformation of the multi-state is divided into two types of upward transformation and downward transformation
1, upward transformation: When there are sub-class objects assigned to a parent class reference, is the upward transformation, polymorphism itself is the process of upward transformation.
Use Format: Parent class type variable name = new subclass type ();
such as Person p = new Student(); :
2, down transformation: a sub-class object that has been transformed upward can use the format of coercion type conversion, the parent class reference to the subclass reference, the process is a downward transformation. If you create a parent class object directly, you cannot change it down!
Use format:
Subclass Type variable name = (subclass type) A variable of the parent class type;
such as Person p = new Student(); 
Student stu = (Student) p
:
the advantages and disadvantages of polymorphism
when a reference to a parent class is directed to a subclass object, an upward transformation occurs, that is, the object of the class type is converted to the parent class type. The benefit of the upward transformation is the hidden subclass type, which increases the extensibility of the code. But the upward transformation also has the disadvantage, can only use the parent class common content, but cannot use the subclass characteristic function, the function has the limitation. Look at the following code:

Describe the animal class and extract the common Eat methodAbstractClassAnimal {Abstractvoid eat ();}Describe dog class, inherit animal class, Rewrite Eat method, add Lookhome methodClassDogExtendsAnimal {void Eat () {System.out.println ("Chew Bones"); }void Lookhome () {System.out.println ("Housekeeping"); }}Describe the cat class, inherit the animal class, rewrite the Eat method, increase the Catchmouse methodClassCatExtendsAnimal {void Eat () {System.out.println ("Eat fish"); }void Catchmouse () {System.out.println ("Catch the Mouse"); }}PublicClasstest {public static void main (string[] args) {Animal a = new Dog (); //polymorphic form, creates a dog object A.eat (); //the method in the calling object, the Eat method in the dog class is executed //a.lookhome ();//using the Dog class-specific method, needs to be transformed downward, not directly using the //in order to use the Lookhome method of dog class, need to transition downward //down the transition process, A type conversion error may occur, that is, the classcastexception exception //then, you need to make a robust judgment before turning if (!a instanceof dog) {//to determine whether the current object is a Dog type System.out.println (" Type mismatch, Cannot be converted "); return;} Dog d = (dog) A; //downward Transformation d.lookhome (); //call the Dog class Lookhome method}}           

Let's sum it up:
1, when to use the upward transformation:
When you do not have to face a subclass type, you can use the upward transformation by increasing extensibility, or by using the functionality of the parent class to accomplish the appropriate action.
Such as:

a = new Dog();a.eat();

2. When to use downward transformation
When you want to use subclass-specific functionality, you need to use a downward transformation.
Such as:

a; //向下转型d.lookHome();//调用狗类的lookHome方法

3. Benefits of downward transformation: You can use subclass-specific features.
4, the downside of transformation: the need to face specific sub-class objects, in the downward transition prone to classcastexception type conversion exception. Type judgments must be made before the conversion.
Such as:if( !a instanceof Dog){…}

Java Polymorphism (i)

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.