A detailed description of Java polymorphism

Source: Internet
Author: User

1. What is polymorphic?

Multiple states of an object

Like what:

Teacher a = old clock;

Staff b= old clock;

2. Polymorphic Manifestation

(1)Father class

non-static member variable x

Static member variables y

non-static methods Eat, method Body Output Parent class information

Static Methods speak (); method Body Output Parent class information

(2):Son class

non-static member variable x

Static member variables y

non-static methods Eat , method body output sub-class information

Static Methods speak (); method Body Output sub-class information

Class Father {int x = 1;static int y = 2;void eat () {System.out.println ("open Eat");} static void Speak () {System.out.println ("small head Father");}} Class Son extends Father {int x = 3;static int y = 4;void eat () {System.out.println ("Big head Son can Eat");} static void Speak () {System.out.println ("Big head Son.") ");}} Class Demo {public static void main (string[] args) {Father f = new Son ();//The parent class reference points to the subclass object. System.out.println (f.x); System.out.println (F.Y); F.eat (); F.speak (); }}

Son class Inherits parent class

1: Create Father f=new Son ();

This is where the parent class reference refers to the child class object.

Consider the following questions:

Ask f.x=? (non-static)--1

Ask f.y=? (Static)--2

Ask f.eat () is the output a subclass or parent information? (non-static)----sub-class

Ask F.speak () is the output a subclass or parent information? (static)----Parent class

Run effect


Then why is there such a result? Look at the summary below ~

3. Summary:

(1) When the parent class and subclass have the same non-static member variable, the member variable of the parent class is accessed under polymorphic

(2) When the parent class and child class have the same static member variable, the static member variable of the parent class is accessed under polymorphic

So: the parent class and subclass have the same member variable, and the member variables of the parent class are accessed under polymorphic conditions.

(3) When the parent and child classes have the same non-static method (that is, the subclass overrides the parent class method), the member method of the subclass is accessed under polymorphic conditions.

(4) When the parent class and child class have the same static method (that is, the subclass overrides the parent static method), the static method of the parent class is accessed under polymorphic conditions.

4. Polymorphic Manifestation-Summary:

(1) The parent class reference variable points to the object of the child class

(2) A parent class reference can also accept its own subclass object

5. Multi-State premise:

A relationship between a class and a class that inherits or implements

6. Polymorphic drawbacks

Increase extensibility, but only the parent class reference can be used to point to the parent class member.

7. Polymorphic features

Non-static

(1) Compile time, refer to the reference type variable belongs to the class whether there is a method to call, if there is a compilation pass. No compilation failed

(2) The operation period, the reference object belongs to the class whether there is a method called.

(3) In short, the member function in polymorphic call, compile look to the left, run look to the right.

In polymorphism, the feature of the member variable, regardless of the compilation and run reference to the left (the class to which the reference variable belongs).

In polymorphic, static member functions are characterized by reference to the left of both compilation and operation

8. The role of polymorphism

(1) polymorphism can be used as a formal parameter to accept a wider range of objects, avoiding excessive use of function overloading.

/* 1: Defines the function, depending on the area and perimeter of the output of any graphics. The subclass overrides the abstract method of the parent class, which executes the non-static method of the subclass under polymorphism. 2: polymorphic can be a return value type. Get any Car object 3: Abstract classes and interfaces can be the parent class reference types in polymorphism. */abstract class Myshape{public abstract double Getarea ();p ublic abstract double Getlen ();} Class Rect extends myshape{double width;d ouble height; Rect () {}rect (double width, double height) {this.width=width;this.height=height;} Public double Getarea () {return width*height;} Public double Getlen () {return (width+height);}}  Class Circle extends myshape{double R; public static final double pi=3.14; Circle () {} circle (double R) {this.r=r;} Public double Getlen () {return 2*pi*r;} Public double Getarea () {return pi*r*r;}} Class Demo{public static void Main (string[] args) {System.out.println ();p rint (new Rect (3,4));//myshape m =new Rect (3,4);     Print (New Circle (3));      }//Based on the user's incoming graphic object, calculate the area and perimeter of the graph//1: Polymorphism can be used as a formal parameter, accepting a wider range of objects, to avoid excessive use of function overloading.     public static void print (MyShape m) {System.out.println (M.getlen ());     System.out.println (M.getarea ()); }   }


(2) polymorphic can be used as return value type

/* Get any Car object 1: Defines the car class, has the name and color, provides the parameter and the non-parametric structure, has the operation behavior. 2: Defines the BMW class, inherits the car class, provides a parameterless construct and has a parameter construct (super parent class constructs), overrides the parent class run behavior. 3: Defines the Benz class, inherits the car class, provides the parameterless construct and the argument construct (super parent class constructs), overrides the parent class to run the behavior. 4: Defines the BSJ class, inherits the car class, provides the parameterless construct and the argument construct (super parent class constructs), overrides the parent class to run the behavior. 5: Define static methods, car factories, random production cars. Use the Polymorphic definition method to return a value type. 1: Use (int) Math.Round (Math.random ()); Generates a random number between 0-2. Math Class 2: Use if else to judge, specify, 0,1,2 new cars and return. 6: Call this method to discover the benefits of polymorphism. */class Car {String name; String color; Car () {}car (string name, string color) {this.name = Name;this.color = color;} void Run () {System.out.println ("Run ....") ");}} Class BMW extends Car {BMW () {}BMW (string name, string color) {super (name, color);} void Run () {System.out.println ("BMW is pulling the wind .... ");}} Class Benz extends Car {Benz () {}benz (string name, string color) {super (name, color);} void Run () {System.out.println ("Mercedes-Benz Business preferred ....") ");}} Class Bsj extends Car {bsj () {}BSJ (string name, string color) {super (name, color);} void Run () {System.out.println ("the first choice ....") ");}} Class Demo {public static void main (string[] args) {int x = 0;while (x < D) {Car c = carfactory (); C.run ();x + +;}} Define static methods, car factories, and randomly produce cars. Use the Polymorphic definition method to return a value type. Using random numbers, 0.1.2 if 0 bsj 1 BMW 2 bcpublic static Car carfactory () {int x = (int) math.round (Math.random () * 2); if (0 = = x) {return new BMW ("BMW X6", "Red");} else if (1 = = x) {return new Benz ("Mercedes", "Black"),} else if (2 = = x) {return new BSJ ("Porsche", "Brown"),} else {return new Benz ("Sma RT "," Red ");}}}

(3) Abstract classes and interfaces can be the parent class reference types in polymorphism.

See the first example of a function ~

9. polymorphic Type Conversions

How to invoke a subclass-specific method with a parent class reference in polymorphic mode.

(1) Basic type conversion:

Automatic: Small - Big

Mandatory: Big - Small

(2) class type conversions

Prerequisite: Inheritance, must have a relationship

Auto: Subclass to Parent class

Strong turn: Parent class rotor class

Class Father {void Method1 () {System.out.println ("This is the parent Class 1");} void Method2 () {System.out.println ("This Is parent Class 2");}} Class Son extends Father {void method1 () {System.out.println ("This is subclass 1");} void Method3 () {System.out.println ("This is subclass 3");}} Class Demo {public static void main (string[] args) {Father f = new Son (); f.method1 ();//This is a subclass 1f.method2 ();//This is the parent class 2//f.me Thod3 (); Compile an error. Polymorphic disadvantage, you can only use the parent class reference to point to the parent class member. Class type conversion Son s = (son) f;s.method3 (); System.out.println ();}}



Well, the polymorphism will be finished ~

A detailed description of Java polymorphism

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.