Java polymorphism with a few words can be interpreted intuitively?

Source: Internet
Author: User

In a nutshell, there are different states in the process of doing things. Let me give you an example of how to join Mulan in the Army as a textbook to help you understand. There are three prerequisites for polymorphic existence:
1. To have an inheritance relationship
2. Subclasses to override methods of the parent class
3. Parent class references to child class pairs,
But there are a lot of details to note. First we define two classes, one parent class animal, and one subclass cat.
Parent class Animal

ClassAnimal{IntNum=10;StaticIntAge=20;PublicvoidEat(){Systemout. ( "animal Eats"  public static void sleep () Span class= "o" >{system. Out. ( "animals Sleeping" } public void run () {systemout. ( "animals in the Run" }               /span>                


Sub-class Cat

ClassCatExtendsAnimal{IntNum=80;StaticIntAge=90;StringName="TomCat";PublicvoidEat(){System.out. ( "Cat eats"  public static void sleep () Span class= "o" >{system. Out. ( "cat sleeping" } public void catchmouse () {< span class= "n" >system.. ( "cat in Catch Mouse" }               /span>                

Test class Demo_test1

ClassDemo_test1{PublicStaticvoidMain(String[]Args){AnimalAm=NewCat();am...//system.out.println (Am.name),//Here first note, will explain .. (am. Numsystem.. (am. Age}             /span>                

The above three-segment code fully embodies the polymorphism of the three prerequisites, namely:
1, there is an inheritance relationship
Cat class inherits the Animal Class
2, subclasses to override the parent class's method
Subclass overrides (override) The parent class two member Method Eat (), sleep ()。 where Eat () is non-static, sleep () is static (static).
3, a reference to the parent data type points to the subclass object. The
Test class demo_test1  animal am = new Cat (); The statement opens a subclass (Cat) object in heap memory and points a reference to the parent class (Animal) in the stack memory to the Cat object. The
to this, satisfies the Java polymorphism the necessary three prerequisites. The
---------------------------------------------------Gorgeous split line------------------------------------------------------------ ----------
If we look at a bit more, we can see the output of the test class above, perhaps a deeper understanding of polymorphism. Guess what the above results are.
You can see that
the subclass cat overrides the non-static member method of the parent class animal am.eat (); the output is: the cat eats. The
subclass overrides the static member method of the parent class (Animal) Am.sleep (); the output is: The animal is sleeping
The parent class (Animal) method Am.run () that is overridden by the Quilt Class (Cat) Outputs the result: animals in the run

 system.. (am. Num//output results 10system.. (am. Age//output result is              

Then we can summarize the characteristics of the multi-State member access according to the above situation:
Member variables
Compile look Left (parent class), run look Left (parent class)
Member Methods
Compile to see left (parent Class), run to see right (subclass). Dynamic binding
Static methods
Compile to see left (parent Class), run look Left (parent class).
(Static and class-dependent, not rewritten, so access is still on the left)
Only non-static member methods, compile look left, run look right
---------------------------------------------------Gorgeous split-line---------------------------------------------------------------- ------
So what are the drawbacks of polymorphism? Some, which is polymorphic, cannot use attributes and methods that are specific to subclasses. Looking at the code above, the subclass cat has a unique property of string name = "TomCat"; And there is a special way to catch mice catchmouse (). But in the test class (Demo_test), we try to call the subclass-specific method Catchmouse () and print the subclass-specific member property string name = "TomCat"; will be an error.

am.catchMouse();System.out.println(am.name);

The reason is the disadvantage of polymorphism, that is: You cannot use subclass-specific member properties and subclass-specific member methods.
--------------------------------------------------Gorgeous split-line----------------------------------------------------------------- -----
What if you want to use the properties that are unique to the cat class in the execution of the code, string name and its unique member method, Catchmouse ()? Then we can put this parent reference to the subclass object of the guy am and then force the change back to cat type. So am is a cat type reference, pointing to a Cat object, you can naturally use all the properties of the cat class and all the member methods.

ClassDemo_test{PublicStaticvoidMain(String[]Args){AnimalAm=NewCat();Am.Eat();Am.Sleep();Am.Run();Am.catchmouse ();System.out.println (Am.name);System.Out.println(Am.Num);System.Out.println(Amagesystem.. ( "------------------------------" ct =  (cat) am< Span class= "O"; ct....               /span>                

Obviously, a strong-turn statement is performed by cat ct = (cat) am; then the CT points to the cat type object that was first created in heap memory. This is the charm of polymorphism, although it has shortcomings, but it is very flexible, reduce the creation of redundant objects, needless to say, in order to use a subclass of a method to re-heap the memory of a new sub-class object. Above..
----------------------------------------------------------Split Line------------------------------------------------------------ ------------
Cheer up, get so much praise. I'm surprised to give you an example of a popular point.
Mulan joined the Army for the Father
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 properties 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 herself was using 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. Omg! Finally, we can finally use their own unique member method ' whitewash '. Since then, Mulan completely returned to the father in the Army before the Mulan. And happy with his beloved man over the life. Downward transformation in-----polymorphism
----------------------------------------------------------Gorgeous split-line--------------------------------------------------------- ------
We remember Kazakhstan, the upward transformation of the downward transformation must be in the multi-state of the premise of Kazakhstan, or force the daughter into a father, or the father into a woman, will become the east undefeated, the system at this time will be an error in the illegal type conversion. hahaha haha. In addition, it is generally used to make use of Polymorphic declaration form parameters and to create anonymous objects of subclasses as actual parameters. Above.

Java polymorphism with a few words can be interpreted intuitively?

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.