Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java polymorphism


May 10, 2021 Java


Table of contents


Java polymorphism


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

Polymorphism is the embodiment of many forms of expression of objects.

For example, when we say "pet" object, it has many different expressions or implementations, such as kittens, puppies, lizards and so on. T hen I go to the pet shop and say, "Please give me a pet", the waiter gives me kittens, puppies or lizards, and we say "pets" are polymorphic.

Let's look at Java's polymorphisms with examples.

Example

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Because the Deer class has multiple inheritances, it is polymorphic. T he above examples are parsed as follows:

  • A Deer IS-A (yes) Animal
  • A Deer IS-A (one) Vegetarian
  • A Deer IS-A (yes) Deer
  • A Deer IS-A (one) Object

In Java, all objects are polymorphic because any object can pass the IS-A test type and the Object class.

The only way to access an object is through a reference variable.

There can only be one type of reference variable, and once declared, the type of reference variable cannot be changed.

Reference variables can not only be reset to other objects, as long as they are not declared final. Y ou can also refer to objects of the same or compatible type. It can be declared as a class type or an interface type.

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

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

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


virtual method

We'll show you how the behavior of override methods affects polymorphism in Java when designing classes.

We've already discussed method overrides, which are ways in which children can override parent classes.

When a child class object calls an overrided method, it calls a method of a child class, not a method that is overriding in the parent class.

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

/* 文件名 : 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("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;
   }
}

Suppose the following class inherits the Employee class:

/* 文件名 : Salary.java */
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()
   {
       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;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

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

/* 文件名 : VirtualDemo.java */
public class VirtualDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("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();
    }
}

The above examples compile and run as follows:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

In the example, we instantiated two Salary objects. One uses Salary references and the other uses Employee references.

At compile time, the compiler checks to the declaration of the mailCheck() method in the Salary class.

When calling s.mailCheck(), the Java virtual machine (JVM) calls the mailCheck() method of the Salary class.

Because e is a reference to Employee, calling e's mailCheck() method has completely different results.

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

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.

This behavior is called a virtual method call, and the method is called a virtual method.

All methods in Java behave in this way, allowing override methods to be called at runtime, regardless of the data type in the source code reference variables at compile time.

Polymorphic implementation

Mode 1: Rewrite:

This has been detailed in the previous section and is no longer covered, and is accessible in detail: Override and Overload.

Mode 2: Interface

  • 1. The most representative interface in life is the socket, for example, a three-connector plug can be connected to a three-hole socket, because this is each country has its own rules of interface, it is possible to go abroad not to do, that is because foreign countries define their own interface type.
  • 2.java interfaces in a computer are similar to those in life, a collection of method features, but without a method implementation. You can see exactly what this section of the java interface is about.

Method three: Abstract classes and abstract methods

For more information, see the Java Abstract Class section