多态性是对象表现为多种形式的能力。OOP中多态性最常见的用法是使用父类引用子类对象 。
如果引用变量未声明为final,则可以将其重新分配给其他对象 。引用变量的类型将确定它可以在对象上调用的方法。
让无涯教程看看一个例子。
public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{}
现在,Deer类被认为是多态的,因为它具有多重继承,以下声明是合法的-
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java-polymorphism.html
来源:LearnFk无涯教程网
Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d;
所有引用变量d,a,v,o都引用堆中的相同Deer对象 。
已经讨论了方法重写,其中子类可以重写其父类中的方法。被重写的方法本质上隐藏在父类中,除非子类在重写方法中使用super关键字,否则不会调用该方法。
/* File name : 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; } }
现在假设无涯教程扩展Employee类,如下所示-
/* File name : 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("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; } }
现在,您仔细研究以下程序并尝试确定其输出-
/* File name : 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(); } }
这将产生以下输出-
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
这种行为称为虚方法调用,而这些方法称为虚方法。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)