Latest web development tutorials

Java polymorphism

Polymorphism is the ability to have the same behavior of a number of different forms or morphology.

Polymorphism is the object of many forms of expression.

In reality, such as we press the F1 key to this action:

  • If the current in the Flash pop-up interface is AS 3 help documentation;
  • If the current is in the eject Word Word Help;
  • In the pop-up Windows is Windows Help and Support.

The same event on different objects will produce different results.

Three necessary conditions for the existence of polymorphism:

  • inherit
  • Rewrite
  • Parent reference to a subclass object

such as:

Parent p = new Child();

When using polymorphic method calls the way, first check whether there is the method of the parent class, and if not, the compiler error; if there is, again, calls the same method subclass.

Multi-state benefits: You can make the program a good extension, and can handle all the common objects of the class.

The following presentation is a multi-state instance details, see Note:

public class Test {
    public static void main(String[] args) {
      show(new Cat());  // 以 Cat 对象调用 show 方法
      show(new Dog());  // 以 Dog 对象调用 show 方法
                
      Animal a = new Cat();  // 向上转型  
      a.eat();               // 调用的是 Cat 的 eat
      Cat c = (Cat)a;        // 向下转型  
      c.work();        // 调用的是 Cat 的 catchMouse
  }  
            
    public static void show(Animal a)  {
      a.eat();  
        // 类型判断
        if (a instanceof Cat)  {  // 猫做的事情 
            Cat c = (Cat)a;  
            c.work();  
        } else if (a instanceof Dog) { // 狗做的事情 
            Dog c = (Dog)a;  
            c.work();  
        }  
    }  
}

abstract class Animal {  
    abstract void eat();  
}  
  
class Cat extends Animal {  
    public void eat() {  
        System.out.println("吃鱼");  
    }  
    public void work() {  
        System.out.println("抓老鼠");  
    }  
}  
  
class Dog extends Animal {  
    public void eat() {  
        System.out.println("吃骨头");  
    }  
    public void work() {  
        System.out.println("看家");  
    }  
}  

The above program, the output is:

吃鱼
抓老鼠
吃骨头
看家
吃鱼
抓老鼠

Virtual methods

We will introduce in Java, when designing class action is overridden method of how it affects polymorphism.

We have already discussed the override method, which is a subclass can override the parent class.

When a subclass object calls the overridden method, call the subclass method, rather than the parent class overridden methods.

To call the parent class method is overridden, 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("Employee 构造函数");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public void mailCheck() {
      System.out.println("邮寄支票给: " + 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;
   }
}

Assuming the following class inherits Employee class:

/* 文件名 : Salary.java */
/* 文件名 : Salary.java */
public class Salary extends Employee
{
   private double salary; // 全年工资
   public Salary(String name, String address, int number, double salary) {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck() {
       System.out.println("Salary 类的 mailCheck 方法 ");
       System.out.println("邮寄支票给:" + getName()
       + " ,工资为:" + salary);
   }
   public double getSalary() {
       return salary;
   }
   public void setSalary(double newSalary) {
       if(newSalary >= 0.0) {
          salary = newSalary;
       }
   }
   public double computePay() {
      System.out.println("计算工资,付给:" + getName());
      return salary/52;
   }
}

Now we read the following code tries to give its output:

/* 文件名 : VirtualDemo.java */
public class VirtualDemo {
   public static void main(String [] args) {
      Salary s = new Salary("员工 A", "北京", 3, 3600.00);
      Employee e = new Salary("员工 B", "上海", 2, 2400.00);
      System.out.println("使用 Salary 的引用调用 mailCheck -- ");
      s.mailCheck();
      System.out.println("\n使用 Employee 的引用调用 mailCheck--");
      e.mailCheck();
    }
}

The above examples compiled results are as follows:

Employee 构造函数
Employee 构造函数
使用 Salary 的引用调用 mailCheck -- 
Salary 类的 mailCheck 方法 
邮寄支票给:员工 A ,工资为:3600.0

使用 Employee 的引用调用 mailCheck--
Salary 类的 mailCheck 方法 
邮寄支票给:员工 B ,工资为:2400.0

Examples Analytical

  • Instance, instantiate two objects Salary: Salary use a reference to s, and the other using Employee references e.

  • When calling s.mailCheck (), the compiler found mailCheck at compile time () in the Salary class, the implementation process JVM calls the Salary class mailCheck ().

  • When calling s.mailCheck (), Java Virtual Machine (JVM) to call Salary classes mailCheck () method.

  • Because e is Employee reference, so the caller's e mailCheck () method when the compiler will go Employee class looks mailCheck () method.

  • At compile time, the compiler uses the Employee class mailCheck () method to verify the statement, but at run time, Java Virtual Machine (JVM) is called Salary class mailCheck () method.

Throughout the above process it is called a virtual method calls, which is called a virtual method.

All Java methods can behave in this manner, therefore, can override the method called at run time, regardless of the source code when compiling a reference variable what type of data.