The implementation mechanism of polymorphism in Java

Source: Internet
Author: User
Tags stub

The concept of polymorphism:

In simple terms, a different state exists in the course of a thing, that is, a reference variable defined by a parent class or interface that points to a subclass or an instance object of a concrete implementation class. The program call method is dynamically bound at run time instead of the method defined in the reference variable's type.

Prerequisites for polymorphic existence:

1, there is inheritance relationship, subclass inherits the parent class;

2, subclasses rewrite the method of the parent class;

3. The parent class reference points to the subclass object.

Specific examples:

1. Define a parent class: Animal

1  Packagedemo;2 3  classanimal{4          intnum = 10;5      Static intAge = 20; 6           Public voideat () {7SYSTEM.OUT.PRINTLN ("Food for the Animals");8      }  9           Public Static voidsleep () {TenSystem.out.println ("Sleeping Animals"); One      } A           Public voidrun () { -System.out.println ("Animal Run"); -      } the}

2. Subclass: Cat Inheritance Animal

1  Packagedemo;2 3  Public classCatextendsanimal{4     intNum=80;5     Static intAge=90;6String name= "TomCat";7 @Override8      Public voideat () {9         //TODO auto-generated Method StubTenSystem.out.println ("The Cat Eats"); One     } A      Public Static voidsleep () { -System.out.println ("The Cat is Sleeping"); -     } the      Public voidCatchmouse () { -         //TODO auto-generated Method Stub -System.out.println ("The Cat catches the mouse"); -     } +}

3. Test class: Test1

1  Packagedemo;2 3  Public classTest1 {4 5      Public Static voidMain (string[] args) {6Animal am=NewCat ();7 am.eat ();8 am.sleep ();9 Am.run ();Ten System.out.println (am.num); One System.out.println (am.age); A         //the following two lines of comments are explained later -         //am.catchmouse (); -         //System.out.println (am.name); the     } -  -}

The above three-segment code fully embodies the prerequisites for polymorphic existence:

1, there is inheritance relationship: Cat class inherits the animal class;

2, subclasses to override the parent class method: Subclass Cat Rewrite (override) The parent class animal two methods eat (), sleep (), where Eat () is the normal method, sleep () is static method (static);

3. The parent class reference points to the subclass object: Animal am=new Cat () in the test class, the statement opens a chunk of memory within the heap to the subclass (cat) and points the reference to the parent class (Animal) in the stack memory to the Cat object.

Results after the test class is run:

Can be seen:

1, the subclass cat overrides the parent class animal common method eat () The output result is "the cat eats";

2, the subclass cat overrides the parent class animal static method the output of sleep () is "Sleeping animals";

3. The normal method run () of the parent class animal of the non-quilt cat rewrite is "animal run";

4, the subclass Cat inherits the parent class animal attribute, the output result is the parent class attribute respectively;

5, the output sub-class cat unique properties and methods will be error.

Therefore, according to the above analysis, we can summarize the characteristics of multi-State member access:

Animal am=new Cat ();

Member variables:

Compile look Left (parent class), run look Left (parent class);

Member Methods:

Compile look Left (parent class), run see right (subclass), enter dynamic binding;

static method:

Compile look Left (parent class), run look Left (parent Class), static method is promoted to class level, not rewrite, so access or look at the parent class;

Polymorphism cannot use attributes and methods that are specific to subclasses, there is a unique attribute string name= "TomCat" in the subclass cat, and there is a special method for catching mice catchmouse (). However, in the test class Test1, an error is encountered when attempting to invoke the unique methods of subclasses and print properties specific to subclasses.

What if you want to use properties and methods that are specific to subclasses? You can cast the subclass object that the parent reference refers to as a subclass cat type, so am is a reference to the cat type of the subclass, pointing to the Cat object, so that you can use some of the properties and methods of the subclass.

1  Packagedemo;2 3  Public classTest1 {4 5      Public Static voidMain (string[] args) {6Animal am=NewCat ();7 am.eat ();8 am.sleep ();9 Am.run ();Ten System.out.println (am.num); One System.out.println (am.age); A         //the following two lines of comments are explained later -         //am.catchmouse (); -         //System.out.println (am.name); theSystem.out.println ("-------------------------"); -Cat ct=(Cat) am; - ct.eat (); - ct.sleep (); + Ct.run (); - ct.catchmouse (); + System.out.println (ct.num); A System.out.println (ct.age); at System.out.println (ct.name); -     } -  -}

After the strong-turn statement cat ct= (CAT) is executed, the CT points to the Cat object that was first created in the heap memory. This is the function of polymorphism, the use of very flexible, feel less the creation of redundant objects, not to use a subclass of a method to go to heap memory to open up a new space for a new subclass object.

Examples of Mulan taking the father to the army:

We all know that Mulan for the father of the Army, Mulan for Father Flower Arc army. So at this time Mulan is a subclass, the flower arc is the parent class. Flower arcs have their own member attribute age, name, gender. Mulan also has these properties, but it is clear that the property values are completely different. The flower arc has its own non-static member method of ' horseback kill ', as well as Mulan also inherited the same method as the father ' horseback kill '. ARC also has a static method of ' self introduction ', everyone can ask the flower arc name. Mulan also has a unique non-static member method of ' whitewash '. However, now Mulan in the army for the father, women disguised as men. At this time the equivalent of a reference to the parent class (the name of the flower arc) points to the subclass object (Mulan, the person), then in other classes (other people) to access the subclass object (Mulan this person) member attributes (name, age, gender), actually see is Mulan her father's name (flower arc), age (60 years), Gender (male). When accessing the non-static member method of the Subclass object (Mulan) (Riding War), I actually saw Mulan use terrorize to fight on horseback. When visiting the static method of Mulan (self-introduction), Mulan uses her father's name information to introduce herself to others. And at this time Mulan could not use its own unique member method ' whitewash '. the upward transformation in----- polymorphism

Then finally one will work millions bone withered, war hit, Mulan Farewell to the war life. One day, met his beloved man, this time the power of love to the parent object of the reference (the name of the flower arc) cast to the child object of the original reference (Mulan this name), then Mulan again became her own, at this time she is completely herself. The name is Mulan, age is 28, sex is female, war still so vigorous female man, self introduction is to tell others my name is Mulan. Finally, you can use your own unique member method ' whitewash '. Since then, Mulan completely returned to the father in the Army before the Mulan. downward transformation in----- polymorphism

The upward transformation of the downward transformation must be in the context of polymorphism, while the upward transformation is safe, downward transformation is not safe. such as forcing the daughter into a father, then the daughter can use the father's identity exists, on the contrary, the father into a daughter, will become the east undefeated, the system will be error-type conversion. In addition, a polymorphic declaration form parameter is generally used in the development, and the anonymous object of the subclass is created as the actual parameter.

The implementation mechanism of polymorphism in Java

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.