Introduction to Java - Object Oriented - 03. Polymorphism

Posted by moonoo1974 on Sat, 07 Mar 2020 06:05:51 +0100

Original address: http://www.work100.net/training/java-polymorphism.html
More Tutorials: Beam Cloud - Free Course

polymorphic

Sequence Number Intratext chapters video
1 Summary -
2 virtual function -
3 Implementation of polymorphism -

See the navigation section above for reading

1. Overview

Polymorphism is the ability of the same behavior to have multiple forms or forms.

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

Polymorphism is the manifestation of many forms of objects.

In reality, like when we press the F1 key:

  • If the current pop-up under the Flash interface is the help document for AS 3
  • If the current popup under Word is Word Help
  • Windows Help and Support pops up under Windows
  • The same event happens on different objects with different results

Advantages of polymorphism

  • Eliminating coupling between types
  • Replaceability
  • Scalability
  • Interface
  • flexibility
  • Simplification

Three Necessary Conditions for the Existence of Polymorphisms

  • inherit
  • Rewrite
  • Parent Reference Points to Subclass Object

For example:

Parent p = new Child();

When a method is invoked in a polymorphic manner, it is first checked to see if there is a method in the parent class, if not, a compilation error occurs, and if so, the method with the same name of the subclass is invoked.

Benefits of polymorphism: You can make your program well extended and use it for all classes of objects.

The following is a demonstration of a polymorphic instance, detailed in the comments:

public class Test {
    public static void main(String[] args) {
      show(new Cat());  // Call show method with Cat object
      show(new Dog());  // Call show method with Dog object

      Animal a = new Cat();  // Upward Transition  
      a.eat();               // Cat's eat was called
      Cat c = (Cat)a;        // Downward transition  
      c.work();        // Called 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) { // What Dogs Do 
            Dog c = (Dog)a;  
            c.work();  
        }  
    }  
}

abstract class Animal {  
    abstract void eat();  
}  

class Cat extends Animal {  
    public void eat() {  
        System.out.println("Eat fish");  
    }  
    public void work() {  
        System.out.println("Catching mice");  
    }  
}  

class Dog extends Animal {  
    public void eat() {  
        System.out.println("Eat Bones");  
    }  
    public void work() {  
        System.out.println("Housekeeping");  
    }  
}

Execute the above program and the output is:

Eat fish
 Catching mice
 Eat Bones
 Housekeeping
 Eat fish
 Catching mice

2. Virtual Functions

Virtual functions exist for polymorphism.

There is no concept of virtual function in Java. Its normal function is equivalent to C++ virtual function. Dynamic binding is the default behavior of Java.If you don't want a function to have a virtual function feature in Java, you can add the final keyword to make it non-virtual.

Rewrite

We will describe how the behavior of overridden methods affects polymorphism in Java when designing classes.

We have discussed method overrides, which means that a subclass can override a parent class's method.

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

To invoke overridden methods in the parent class, the keyword super must be used.

Employee.java file code:

/* Filename: Employee.java */
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() {
      System.out.println("Mail 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;
   }
}

Suppose the following class inherits the Employee class:

Salary.java file code:

/* Filename: Salary.java */
public class Salary extends Employee
{
   private double salary; // Annual wages
   public Salary(String name, String address, int number, double salary) {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck() {
       System.out.println("Salary Class mailCheck Method ");
       System.out.println("Mail check to:" + getName()
       + " ,Wages are:" + salary);
   }
   public double getSalary() {
       return salary;
   }
   public void setSalary(double newSalary) {
       if(newSalary >= 0.0) {
          salary = newSalary;
       }
   }
   public double computePay() {
      System.out.println("Calculate wages paid to:" + getName());
      return salary/52;
   }
}

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

VirtualDemo.java file code:

/* Filename: VirtualDemo.java */
public class VirtualDemo {
   public static void main(String [] args) {
      Salary s = new Salary("staff A", "Beijing", 3, 3600.00);
      Employee e = new Salary("staff B", "Shanghai", 2, 2400.00);
      System.out.println("Use Salary Reference Call mailCheck -- ");
      s.mailCheck();
      System.out.println("\n Use Employee Reference Call mailCheck--");
      e.mailCheck();
    }
}

The above example compiles and runs as follows:

Employee constructor
 Employee constructor
 Call mailCheck with Salary's reference -- 
mailCheck method of Salary class 
Mail check to: Employee A, salary: 3600.0

Call mailCheck with Employee's reference--
mailCheck method of Salary class 
Mail check to: Employee B, salary: 2400.0

Example Analysis

In the instance, two Salary objects are instantiated: one using the Salary reference s and the other using the Employee reference e.

When s.mailCheck() is called, the compiler finds mailCheck() in the Salary class at compile time, and the execution process JVM calls mailCheck() in the Salary class.

Because e is a reference to Employee, when e's mailCheck() method is called, the compiler goes to the Employee class to find the mailCheck() method.

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 entire process described above is called a virtual method call, which is called a virtual method.

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

3. Implementation of Polymorphism

Mode 1: Rewrite

This content, which has been detailed in the previous chapter, is no longer covered and is accessible in detail: Java Override and Overload.

Mode 2: Interface

  • The most representative interface in life is the socket, for example, a three-connector plug can be connected in a three-socket socket, because each country has its own set of interface rules, which may not work abroad because of the interface type defined by foreign countries.
  • An interface in Java is like an interface in life, a collection of method features but no method implementation.You can see the Java interface section in detail.

Mode three: abstract classes and methods

See details abstract class Chapter.

Last: Rewrite and overload
Next: abstract class

Topics: Java socket Windows jvm