七叶笔记 » java编程 » Java 实现多态的机制是什么?

Java 实现多态的机制是什么?

Java多态的实现机制是什么

Java中实现多态的机制是依靠父类或接口的引用指向子类,从而实现一个对象多种形态的特性,其父类的引用是在运行时动态的指向具体的实例,调用该引用的方法时,不是根据引用变量的类型中定义的方法来运行,而是根据具体的实例的方法。

简单的示例

Person.java

import java.util.Scanner;public class Person {    public int salary;    public int allSalary(){        return 0;    }    public static void main(String[] args) {        Person p = null;        for (int n = 0; n < 3; n++) {            @SuppressWarnings("resource")            Scanner sc = new Scanner(System.in);            System.out.println("请输入一个1-3的数字:\n1 is Teacher\n2 is Scientis\n3 is Waiter");            int i = sc.nextInt();            //分别指向了不同的子类,输出的结果是不一样的            if (i == 1) {                p = new Teacher(5000);                System.out.println(p.allSalary());            } else if (i == 2) {                p = new Scientist(5000);                System.out.println(p.allSalary());            } else if (i == 3) {                p = new Waiter(5000);                System.out.println(p.allSalary());            } else {                System.out.println("?\n请输入1-3");            }        }}}

Scientist .java

 public class Scientist extends Person{    public Scientist(int salary){        this.salary = salary;    }    public int allSalary(){        int aa = salary*12+36500;        System.out.print("五五开一年的工资:");        return aa;    }}

Waiter.java

public class Waiter extends Person{    public Waiter(int salary){        this.salary = salary;    }    public int allSalary(){        int aa = salary*12;        System.out.print("服务员一年的工资:");        return aa;    }}

Teacher .java

public class Teacher extends Person{    public Teacher(int salary){        this.salary = salary;    }    public int allSalary(){        int aa = salary*12+3650;        System.out.print("教师一年的工资:");        return aa;    }}

推荐教程:《Java教程》

相关文章