Introduction to JavaSE 18: Java object-oriented Polymorphism

Source: Internet
Author: User

Introduction to JavaSE 18: Java object-oriented Polymorphism
Java Polymorphism

Polymorphism is the ability of a single behavior to have multiple different forms or forms. Polymorphism is a manifestation of multiple forms of objects. For example, we say "Pet"

Object, it has many different expressions or implementations, such as a kitten, a puppy, a lizard, and so on. Then I went to the pet store and said, "Please give me a pet ",

The waiter can give me a kitten, a puppy, or a lizard. We can say that the "Pet" object has polymorphism.

Next, let's learn about Java polymorphism through examples.

Instance:

Source code of Vegetarian. java:

Public interface Vegetarian {// Implementation Details}

Animal. java source file code:

Public class Animal {// Implementation Details}

Deer. java source file code:

Public class Deer extends Animal implements Vegetarian {// Implementation Details}

Because the Deer class has multiple inheritance, it has polymorphism. The above example is parsed as follows:

A Deer IS-A (a) Animal

A Deer IS-A (is a) Vegetarian

A Deer IS-A (a) Deer

A Deer IS-A (a) Object

In Java, all objects are subject to polymorphism because any Object can test the type and Object class through the IS-A. This can be used later

Instanceof keyword to verify.

The only way to access an object is to reference a variable. Only one type can be referenced. Once declared, the type of referenced variable is

Cannot be changed. Referenced variables can be reset to other objects only if they are not declared as final. You can also reference

The same or compatible objects. It can be declared as a class type or an interface type.

When we apply a referenced variable to a Deer object reference, the following statement is legal:

Deer d = new Deer ();

Animal a = d;

Vegetarian v = d;

Object o = d;

All referenced variables d, a, v, and o point to the same Deer object in the heap.

Binary imaginary Method

In Java, how does the behavior of overloaded methods affect polymorphism when designing classes. We have discussed method overloading, that is, the ability of subclass to overload

The method of the parent class. When a subclass object calls an overloaded method, it calls the subclass method instead of the overloaded method in the parent class.

To call a method that is overloaded in the parent class, you must use the keyword "super.

Instance:

Source File Code of Employee. java:

Public class Employee {// private member variable private String name; private String address; private int number; // constructor public Employee (String name, String address, int number) {System. out. println ("Constructing an Employee"); this. name = name; this. address = address; this. number = number;} public void mailCheck () {System. out. println ("Mailing a check to" + this. name + "" + this. address);} public String toString () {return name + "" + address + "" + number;} public String getName () {return name;} public String getAddress () {return address;} public void setAddress (String newAddress) {address = newAddress;} public int getNumber () {return number ;}}

Assume that the following Salary class inherits the Employee class:

Source File Code of Salary. java:
Public class Salary extends Employee {// private member variable private double salary; // Annual salary // constructor public Salary (String name, String address, int number, double salary) {// inherit the member variable super (name, address, number); setSalary (salary);} // override mailCheck () of the parent class Employee () method public void mailCheck () {System. out. println ("Within mailCheck of Salary class"); System. out. println ("Mailing check to" + getName () + "with salary" + salary);} public double getSalary () {return salary;} public void setSalary (double newSalary) {if (newSalary >=0.0) {salary = newSalary ;}// the public double computePay () method exclusive to the sub-class Salary class {System. out. println ("Computing salary pay for" + getName (); return salary/52 ;}}
Now, read the following code carefully and give the output result:
VirtualDemo. java source file code:
Public class VirtualDemo {public static void main (String [] args) {// instantiate the object s of the Salary class (reference of this class points to the object of this class) salary s = new Salary ("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); // instantiate the Object e of the Employee class (the parent class references the object pointing to the subclass) employee e = new Salary ("John Adams", "Boston, MA", 2, 2400.00); System. out. println ("Call mailCheck using Salary reference --"); // Call this class method s when creating this class object. mailCheck (); System. out. println ("\ n Call mailCheck using Employee reference --"); // when a subclass object is created, the method called is the method rewritten by the subclass or the inherited method e. mailCheck ();}}
The above example compilation and running results are as follows:

Example:

In this example, we instantiate two Salary objects. One uses the Salary class of this class to reference s, and the other uses the parent class to reference Employee class.

During compilation, the compiler checks the declaration of the mailCheck () method in the Salary class. When s. mailCheck () is called, Java Machine (JVM) calls Salary

The mailCheck () method of the class. Because e is a reference of Employee, the emailCheck () method called has completely different results.

When the compiler checks the e. mailCheck () method, the compiler checks the mailCheck () method in the Employee class. During compilation, the compiler enables

The mailCheck () method in the Employee class is used to verify the statement. However, when running, the Java Virtual Machine (JVM) calls

MailCheck () method. This action is called a virtual method call, which is called a virtual method.

All methods in Java can be expressed in this way. In this way, the rewrite method can be called at runtime, regardless of the variables referenced in the source code during compilation.

What is the data type.

Summary of three-sided object Polymorphism

1 Reference Polymorphism

The reference of this class can point to the objects of this class.

A reference to a parent class can point to a subclass object.

2 method Polymorphism

The method called when creating this class object is this class method.

When a subclass object is created, the method called is the method rewritten by the subclass or the inherited method.

Here is an example of converting the reference type in the four polymorphism:
Animal. java source file code:
Public class Animal {public String name; public int age; public Animal () {System. out. println ("I am an Animal class constructor ");}}
Dog. java source file code:
Public class Dog extends Animal {public Dog () {System. out. println ("I am a Dog class constructor ");}}
Test. java source file code:
Public class Test {public static void main (String [] args) {// instantiate Animal class Animal a1 = new Animal (); // The parent class references the Animal a2 = new Dog () object pointing to this class (); // reference the parent class to the subclass object // instantiate the Dog class Dog d1 = new Dog (); // The subclass points to the Class Object Dog d2 = new Animal (); // subclass refers to the parent class object. This compilation will cause a problem }}
Compilation result:

We can use the instanceof operator to determine the object type:

Rewrite the source code of Test. java:
Public class Test {public static void main (String [] args) {// instantiate Animal class Animal a1 = new Animal (); // The parent class references the Animal a2 = new Dog () object pointing to this class (); // reference the parent class to the subclass object // instantiate the Dog class d1 = new Dog (); // subclass points to the object of this class // Dog d2 = new Animal (); // subclass to the object of the parent class, this compilation will cause problems System. out. println (a1 instanceof Animal); System. out. println (a2 instanceof Animal); System. out. println (d1 instanceof Dog );}}
Running result:
Summary of reference type conversion

1) Up-type conversion (implicit or automatic type conversion) is a conversion from small type to large type. There is no security issue.

2) downward type conversion (forced type conversion) is a conversion from a large type to a small type. Security issues exist. Data overflow.

3) The instanceof operator is used to determine the type of the referenced object to avoid the security of type conversion.

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.