Java Basics (eight): polymorphic

Source: Internet
Author: User

One, polymorphic understanding:

Polymorphism is the ability of the same behavior to have many different manifestations or forms.

Polymorphism is the same interface that uses different instances to perform different operations:

  

Polymorphism is the embodiment of various objects of the object: In reality, for example, we press the F1 button This action: If the current Flash interface is pop-up is the help document as 3; If Word Help is currently popping up under Word, Windows Help and Support: The same event occurs on different objects and produces different results.

Ii. the advantages and conditions of polymorphism:

The advantages of polymorphism: 1. Eliminate the coupling relationship between types 2. Replaceable 3. Scalability 4. Interface 5. Flexibility 6. Simplification of

Three prerequisites for polymorphic presence: 1, inheritance, 2, override 3, parent class reference to child class object

For example:Parent P = new child (); when calling a method using polymorphic mode, first check whether the method is in the parent class, if not, compile the error, and if so, call the subclass's same name method.

The benefits of polymorphism: The program can be well extended, and the objects of all classes can be universally handled. Here is a demonstration of a polymorphic instance, with a detailed description of the note:

 Public classTest { Public Static voidMain (string[] args) {Show (NewCat ());//call the Show method with a Cat objectShowNewDog ());//call the Show method with a Dog objectAnimal a=NewCat ();//Upward TransformationA.eat ();//The Eat of the Cat is calledCat C = (cat) A;//Down TransformationC.work ();//The catchmouse of the Cat is called  }         Public Static voidShow (Animal a) {a.eat (); //Type judgment        if(A instanceof Cat) {//things that cats doCat C =(Cat) A;          C.work (); } Else if(A instanceof Dog) {//What the dog does.Dog C =(Dog) A;          C.work (); }      }  }Abstract classAnimal {Abstract voideat (); }  classCat extends Animal { Public voideat () {System. out. println ("Eat fish"); }       Public voidWork () {System. out. println ("Catch the mouse"); }  }  classDog extends Animal { Public voideat () {System. out. println ("Eat Bones"); }       Public voidWork () {System. out. println ("Housekeeping"); }  }

Third, virtual method:

We will describe how the behavior of the overridden method affects polymorphism in Java when designing a class.

We have discussed the rewriting of methods, that is, subclasses can override the parent class's methods. When a subclass object calls an overridden method, it calls the method of the child class, not the overridden method in the parent class. To invoke a method that is overridden in a parent class, you must use the keyword super.

 Public classEmployee {PrivateString name; PrivateString address; Private intNumber ;  PublicEmployee (string name, address string,intNumber ) {System. out. println ("Employee Constructor");  This. Name =name;  This. Address =address;  This. Number =Number ; }    Public voidMailCheck () {System. out. println ("Mail a cheque to:"+ This. Name+" "+ This. Address); }    PublicString toString () {returnName +" "+ Address +" "+Number ; }    PublicString GetName () {returnname; }    PublicString getaddress () {returnaddress; }    Public voidsetaddress (String newaddress) {address=newaddress; }    Public intGetNumber () {returnNumber ; }}

Assume that the following class inherits the employee class:

 Public classSalary extends employee{Private DoubleSalary//Annual Salary    PublicSalary (string name, string address,intNumberDoublesalary)       {Super (name, address, number);   Setsalary (Salary); }    Public voidMailCheck () {System. out. println ("the MailCheck method of Salary class"); System. out. println ("Mail a cheque to:"+GetName ()+", the salary is:"+salary); }    Public Doublegetsalary () {returnsalary; }    Public voidSetsalary (Doublenewsalary) {       if(Newsalary >=0.0) {Salary=newsalary; }   }    Public DoubleComputepay () {System. out. println ("to calculate wages and pay:"+getName ()); returnsalary/ the; }}

Now let's read the following code carefully and try to give its output:

 Public classVirtualdemo { Public Static voidmain (String [] args) { Salary s = new Salary ("Employee A", "Beijing", 3, 3600.00); Employee E = new Salary ("Employee B", "Shanghai", 2, 2400.00); System. out. println ("call MailCheck with reference to Salary--");      S.mailcheck (); System. out. println ("\ nthe call to mailcheck--using the Employee's reference");    E.mailcheck (); }}

instance, two Salary objects were instantiated: one using Salary reference s and the other using the Employee reference E.

When S.mailcheck () is called, the compiler will find MailCheck () in the Salary class at compile time, and the execution process JVM invokes the MailCheck () of the Salary class.

Because E is a reference to employee, the compiler goes to the employee class to find the MailCheck () method when you call the MailCheck () method of E. At compile time, the compiler validates the statement using the MailCheck () method in the Employee class, but at run time, the Java Virtual machine (JVM) calls the MailCheck () method in the Salary class. ( the method called is always the instance object, regardless of the reference type )

The entire process is called a virtual method call , and the method is called a virtual method.

All methods in Java can behave in this way, so the overridden method can be called at run time, regardless of the data type of the reference variable in the source code at compile time.

Four, polymorphic realization way:

1. Rewrite

2. Interface

3. Abstract classes and abstract methods

Five, Summary:

  For polymorphism, the following points can be summed up:

1. Use a reference to the parent class type to point to the object of the subclass;

2. The reference can only invoke methods and variables defined in the parent class;

3. If a method in the parent class is overridden in a subclass, the method in the subclass will be called when the method is called (Dynamic connection, dynamic invocation);

4. Variables cannot be overridden (overwritten), the concept of "overriding" is only for methods, and if a variable in the parent class is "overridden" in a subclass, an error is made at compile time.

Java Basics (eight): polymorphic

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.