Polymorphism in Java

Source: Internet
Author: User

The following is referenced from http://wiki.jikexueyuan.com/project/java/polymorphism.html:

Polymorphism means that an object can have many forms. The most common polymorphism in OOP occurs when the parent class references a child class object.

Any Java object that can be tested with more than one is-a is considered polymorphic. All objects in Java are polymorphic, because any object will have a is-a relationship of their own type and the object class.

It is important to know that by referencing a variable is the only method that can be used to access an object. A reference variable can have only one type. Once a reference variable is declared, it cannot be changed.

Reference variables can be reassigned to other supplied objects that are not declared final. The type of the reference variable determines the method of the object it can invoke.

A reference variable can refer to either the declared type of any object or a subtype of any claim type. A reference variable can be declared as a class or an interface type.

Example:

Look at the following example:

 Public Interface vegetarian{}  Public class animal{}  Public class extends Implements vegetarian{}

Now the Deer class is polymorphic because he has multiple inheritance mechanisms. For the above example there are the following statements:

    • Deer is animal.
    • Deer is vegetarian.
    • Deer is deer.
    • Deer is an object.

When providing a reference variable to reference the Deer object, the following declaration is valid:

Deer d = new Deer();Animal a = d;Vegetarian v = d;Object o = d;

All reference variables D,a,v,o reference the same object deer in the heap.

One, the virtual method

This will show how the behavior of the overridden method in Java embodies the benefits of polymorphism when designing a class.

A subclass can override the methods of its parent class. A overridden method is actually hidden from the parent class and is not called unless the subclass uses the Super keyword in the overridden method.

/*File Name:Employee.java*/ Public classemployee{PrivateString name; PrivateString address; Private intNumber ;  PublicEmployee (string name, address string,intNumber ) {System.out.println ("Constructing an Employee");  This. Name =name;  This. Address =address;  This. Number =Number ; }    Public voidMailCheck () {System.out.println ("Mailing a check 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 ; }}

Now inherit the employee class as follows:

/*File Name:Salary.java*/ Public classSalaryextendsemployee{Private DoubleSalary//Annual Salary    PublicSalary (string name, string address,intNumberDoublesalary) {       Super(name, address, number);   Setsalary (Salary); }    Public voidMailCheck () {System.out.println ("Within MailCheck of Salary class"); System.out.println ("Mailing Check to" +GetName ()+ "with salary" +salary); }    Public Doublegetsalary () {returnsalary; }    Public voidSetsalary (Doublenewsalary) {       if(Newsalary >= 0.0) {Salary=newsalary; }   }    Public DoubleComputepay () {System.out.println ("Computing salary pay for" +getName ()); returnSalary/52; }}

Now, take a closer look at the following program and try to determine its output:

/*File Name:VirtualDemo.java*/ Public classvirtualdemo{ Public Static voidmain (String [] args) {Salary s=NewSalary ("Mohd Mohtashim", "Ambehta, Up", 3, 3600.00); Employee e=NewSalary ("John Adams", "Boston, MA", 2, 2400.00); System.out.println ("Call MailCheck using Salary reference--");      S.mailcheck (); System.out.println ("\ n call MailCheck using Employee reference--");    E.mailcheck (); }}//this will produce the following results:constructing an employeeconstructing an employeecall mailcheck using Salary reference--within mailcheck of Salaryclassmailing Check to Mohd Mohtashim with salary3600.0Call MailCheck using Employee reference--within mailcheck of Salaryclassmailing Check to John Adams with salary2400.0

This instantiates two salary objects. One uses salary to refer to S, and the other uses an employee to refer to E.

When the S.mailcheck () method is called, the compiler discovers MailCheck () in the salary class at compile time, and the JVM calls the MailCheck () method of the salary class at run time.

Calling E's MailCheck () is slightly different because E is a reference to an employee. When the compiler discovers E.mailcheck (), the compiler discovers the Mail.check () method in the Employee class.

At compile time, the compiler uses the employee's MailCheck () method to validate. At run time, the JVM calls the MailCheck () class of the salary class.

This behavior is called a virtual method call, and the method is also known as a virtual method. All of the method behavior of this rule in Java, regardless of the reference to the data type, calls the overridden method at compile time and follows the source code.

Test Project: https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test19

Polymorphism in Java

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.