polymorphism

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

Polymorphism is the same interface, using different instances to perform different operations, as shown in the figure below:

Polymorphism is the manifestation of multiple forms of objects.

The advantages of polymorphism

  • Decouple the types
  • replaceability
  • scalability
  • Interface,
  • flexibility
  • Simplify the sex

Three necessary conditions for the existence of polymorphism

  • inheritance
  • rewrite
  • Superclass references refer to subclass objects:Parent p = new Child();

class Shape {
    void draw(a) {}}class Circle extends Shape {
    void draw(a) {
        System.out.println("Circle.draw()"); }}class Square extends Shape {
    void draw(a) {
        System.out.println("Square.draw()"); }}class Triangle extends Shape {
    void draw(a) {
        System.out.println("Triangle.draw()"); }}Copy the code

When a method is called in polymorphic mode, the first check is made to see if the method exists in the parent class. If not, a compilation error occurs. If so, call the subclass’s method of the same name.

Benefits of polymorphism: it allows programs to be well extensible and can handle objects of all classes in general.

The instance

public class Test {
    public static void main(String[] args) {
      show(new Cat());  Call the show method with the Cat object
      show(new Dog());  Call the show method on the Dog object
                
      Animal a = new Cat();  // Upward transition
      a.eat();               // 调用的是 Cat 的 eat
      Cat c = (Cat)a;        // Downward transition
      c.work();        // call Cat work
  }  
            
    public static void show(Animal a)  {
      a.eat();  
        // Type judgment
        if (a instanceof Cat)  {  // What cats do
            Cat c = (Cat)a;  
            c.work();  
        } else if (a instanceof Dog) { // Things dogs doDog c = (Dog)a; c.work(); }}}abstract class Animal {  
    abstract void eat(a);  
}  
  
class Cat extends Animal {  
    public void eat(a) {  
        System.out.println("Fish");  
    }  
    public void work(a) {  
        System.out.println("Catch a mouse."); }}class Dog extends Animal {  
    public void eat(a) {  
        System.out.println("Bone eating");  
    }  
    public void work(a) {  
        System.out.println("Housekeeping"); }}Copy the code
Eat fish catch mice eat bones watch the house eat fish catch miceCopy the code

Virtual functions

Virtual functions exist for polymorphism.

In fact, Java does not have the concept of virtual functions, its ordinary functions are equivalent to C++ virtual functions, dynamic binding is the default behavior of Java. If you do not want a function to have virtual function properties in Java, you can add the final keyword to make it non-virtual.


When a subclass object calls an overridden method, it calls the subclass’s method, not the overridden method in its parent class.

To call the overridden method in the parent class, the keyword super must be used.

public class Employee {
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number) {
      System.out.println("Employee constructor");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public void mailCheck(a) {
      System.out.println("Send a check to:" + this.name
       + "" + this.address);
   }
   public String toString(a) {
      return name + "" + address + "" + number;
   }
   public String getName(a) {
      return name;
   }
   public String getAddress(a) {
      return address;
   }
   public void setAddress(String newAddress) {
      address = newAddress;
   }
   public int getNumber(a) {
     returnnumber; }}Copy the code

Suppose the following classes inherit from the Employee class:

public class Salary extends Employee
{
   private double salary; // Annual salary
   public Salary(String name, String address, int number, double salary) {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck(a) {
       System.out.println("Salary 类的 mailCheck 方法 ");
       System.out.println("Send a check to:" + getName()
       + ", the salary is: + salary);
   }
   public double getSalary(a) {
       return salary;
   }
   public void setSalary(double newSalary) {
       if(newSalary >= 0.0) { salary = newSalary; }}public double computePay(a) {
      System.out.println("Calculate wages and pay:" + getName());
      return salary/52; }}Copy the code

Now let’s go through the following code and try to give its output:

public class VirtualDemo {
   public static void main(String [] args) {
      Salary s = new Salary("Employees A"."Beijing".3.3600.00);
      Employee e = new Salary("Employee B"."Shanghai".2.2400.00);
      System.out.println("Call the mailCheck with the Salary reference --");
      s.mailCheck();
      System.out.println("\n Call mailCheck with a reference to Employee --"); e.mailCheck(); }}Copy the code

The compilation and running results of the above examples are as follows:

The Employee constructor calls the mailCheck method of the Salary class with A reference to Salary to mail A check to: Employee A3600.0Call the mailCheck method of the Employee -- Salary class with a reference to Employee to mail a check to: Employee B2400.0
Copy the code

Example:

  • In the instance, two are instantiatedSalaryObject: one useSalaryreferences, another useEmployeereferencee.
  • When callings.mailCheck()When the compiler is compilingSalaryFound in classmailCheck(), execution processJVMJust callSalaryOf the classmailCheck().
  • eEmployeeQuote, but quoteeAnd what’s going to run isSalaryOf the classmailCheck()Methods.
  • At compile time, the compiler usesEmployeeIn the classmailCheck()Method validates the statement, but at run time,JavaVirtual machine (JVM) is calledSalaryIn the classmailCheck()Methods.

This whole process is called a virtual method call, and the method is called a virtual method.

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

The implementation of polymorphism

Method 1: Rewrite:

Mode 2: Interface

  • The most representative interface in life is the socket, for example, a three-connector plug can be connected in the three-hole socket, because this is each country has their own provisions of the interface rules, may not be able to go abroad, that is because of their own definition of the interface type.
  • JavaThe interface is similar to the interface in life, which is a collection of method characteristics, but no method implementation.

Method three: Abstract classes and methods