尚硅谷JavaSE基础

发布时间:2018年11月14日作者:yafei浏览次数:754

6.8.4多态的应用场景

1. 多态数组

   当创建多个不同的子类对象, 而又想统一处理这批对象时, 就可以使用多态数组.

Person[] arr = {new Student(), new Teacher()};

public class Person {  

private String name;

private int age;

private String gender;

public Person(String name, int age, String gender) {

this.name = name;

this.age = age;

this.gender = gender;

}

public void setName(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setAge(int age) {

this.age = age;

}

public int getAge() {

return age;

}

public void setGender(String gender) {

this.gender = gender;

}

public String getGender() {

return gender;

}

public String say() {

return “姓名:” + name + “,年龄:” + age + “,性别:” + gender;

}

public void sayHello() {

System.out.println(“打个招呼”);

}

}

public class Chinese extends Person {

private String shuxiang;

public Chinese(String name, int age, String gender, String shuxiang) {

super(name, age, gender);

this.shuxiang = shuxiang;

}

public void setShuxiang(String shuxiang) {

this.shuxiang = shuxiang;

}

public String getShuxiang() {

return shuxiang;

}

public void spring() {

System.out.println(“过大年”);

}

@Override

public String say() {

return super.say() + “,属相:” + shuxiang;

}

@Override

public void sayHello() {

System.out.println(“吃了吗?”);

}

}

public class American extends Person {

private boolean hasGun;

public American() {}

public American(String name, int age, String gender, boolean hasGun) {

super(name, age, gender);

this.hasGun = hasGun;

}

public void setHasGun(boolean hasGun) {

this.hasGun = hasGun;

}

public boolean isHasGun() {

return hasGun;

}

public void christmas() {

System.out.println(“Merry Christmas!!”);

}

@Override

public void sayHello() {

System.out.println(“How are you?”);

}

}

public class PersonTest {

public static void main(String[] args) {

Person[] ps = new Person[5]; // 多态数组, 可以保存任意类型的子类对象

ps[0] = new Chinese(“张三”, 30, “男”, “牛”);

ps[1] = new American(“Jack”, 25, “male”, true);

ps[2] = new Person(“某人”, 15, “未知”);

ps[3] = new American(“Rose”, 32, “female”, false);

ps[4] = new Chinese(“李四”, 40, “女”, “羊”);

for (Person p : ps) {

System.out.println(p.say());

}

System.out.println(“————————-“);

        // 因为在同一个数组中, 并且所有对象都有age属性, 所以就可以对所有元素进行冒泡排序

for (int i = 0; i < ps.length – 1; i++) {

for (int j = 0; j < ps.length – 1 – i; j++) {

if (ps[j].getAge() > ps[j + 1].getAge()) {

Person tmp = ps[j];

ps[j] = ps[j + 1];

ps[j + 1] = tmp;

}

}

}

for (Person p : ps) {

System.out.println(p.say());

}

}

}


上一篇:
下一篇:
相关课程

java培训 大数据培训 前端培训 UI/UE设计培训

关于尚硅谷
教育理念
名师团队
学员心声
资源下载
视频下载
资料下载
工具下载
加入我们
招聘岗位
岗位介绍
招贤纳师
联系我们
全国统一咨询电话:010-56253825
地址:北京市昌平区宏福科技园2号楼3层(北京校区)

深圳市宝安区西部硅谷大厦B座C区一层(深圳校区)

上海市松江区谷阳北路166号大江商厦6层(上海校区)

武汉市东湖高新开发区东湖网谷(武汉校区)

西安市高新区和发智能大厦(西安校区)