<>多态数组

数组的定义类型为父类类型,里面保存的实际元素类型为子类类型
package com.hspedu.polyarr; public class Person { private String name; private
int age; public Person(String name, int age) { this.name = name; this.age = age;
} public String getName() { return name; } public void setName(String name) {
this.name = name; } public int getAge() { return age; } public void setAge(int
age) { this.age = age; } public String say() { return name + "\t" +age; } }
package com.hspedu.polyarr; public class Student extends Person{ private double
score; public Student(String name, int age, double score) { super(name, age);
this.score = score; } public String say() { return super.say()+"score=" + score;
} } package com.hspedu.polyarr; public class Teacher extends Person{ private
double salary; public Teacher(String name, int age, double salary) { super(name,
age); this.salary = salary; } public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; } //重写父类的方法
@Override public String say() { return super.say() +"salary="+salary; } }
package com.hspedu.polyarr; public class ployArray { public static void main(
String[] args) { Person [] persons = new Person[5]; persons[0] = new Person(
"jack",20); persons[1]= new Student("tom",21,66); persons[2] = new Student(
"heihuj",26,98); persons[3]= new Teacher("semi",18,8734); persons[4] = new
Teacher("ligui",12,5849); //遍历数组 for (int i = 0; i < persons.length ; i++) {
System.out.println( persons[i].say()); //编译类型是persons ,运行类型看后面 //动态绑定 } } }

技术
©2019-2020 Toolsou All rights reserved,
程序员的520,送给女友的几行漂亮的代码(python版)基于stm32控制四轮小车电机驱动(一)linux查看磁盘空间命令实验四 自动化测试工具-软件测试axios拦截器封装与使用C语言——qsort函数opencv-python傅里叶变换以及逆变换在算法研究过程中如何进行算法创新nc的安装和简单操作C语言做一个简易的登陆验证(功能)界面