多态数组 2022-07-20 java 多态数组 0 Comments Word Count: 369(words) Read Count: 2(minutes) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113package com.jhfuture.poly._polyarr__;public class PloyArray { public static void main(String[] args) { Person person[]=new Person[3]; person[0]=new Person("这是个人"); person[1]=new Student("小明",15); person[2]=new Teacher("李老师",1000); for (int i = 0; i <person.length ; i++) { //调用每一个say //输出结果由每一个运行类型决定 person[i].say(); if (person[i] instanceof Student){ ((Student)person[i]).Study(); }else if (person[i] instanceof Teacher){ ((Teacher)person[i]).teacher(); } } }}//应用实例:现有一个class Person{ String name; public Person(String name) { this.name = name; } public void say(){ System.out.println("here is Person"+getName()); } public String getName() { return name; } public void setName(String name) { this.name = name; } Person(){ }}class Student extends Person{ String name; int age; public void say(){ System.out.println("here is Student"+getName()); } public Student(String name, int age) { this.name = name; this.age = age; } public void Study(){ System.out.println("可以学习"); } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}class Teacher extends Person{ String name; double salery; public void say(){ System.out.println("here is Teacher"+getName()); } public Teacher( String name1, double salery) { this.name = name1; this.salery = salery; } public void teacher(){ System.out.println("可以教书"); } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public double getSalery() { return salery; } public void setSalery(double salery) { this.salery = salery; }} 123456//输出here is Person这是个人here is Student小明可以学习here is Teacher李老师可以教书