Java学习笔记——多态数组

例子

Person类(父类)

package poly.array;

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String say(){
        return "name = " + this.name + "\t" + "age = " + this.age;
    }
}

Student类(子类)

package poly.array;

public class Student extends Person{

    private int score;

    public Student() {
    }

    public Student(String name, int age, int score) {
        super(name, age);
        this.score = score;
    }

    @Override
    public String say() {
        return super.say() + "\t" + "score = " + score;
    }
}

Teacher类(子类)

package poly.array;

public class Teacher extends Person{

    private int salary;

    public Teacher() {
    }

    public Teacher(String name, int age, int salary) {
        super(name, age);
        this.salary = salary;
    }

    @Override
    public String say() {
        return super.say() + "\t" + "salary = " + this.salary;
    }
}
package poly.array;

public class Test {
    public static void main(String[] args) {
        Person[] people = new Person[5];
        people[0] = new Student("amei",21,90);
        people[1] = new Person("aha",20);
        people[2] = new Student("marry",30,89);
        people[3] = new Teacher("socro",40,30000);
        people[4] = new Teacher("madalam",79,100000);

        for (Person p:people
             ) {
            System.out.println(p.say());
        }
    }
}

结果

name = amei age = 21 score = 90
name = aha age = 20
name = marry age = 30 score = 89
name = socro age = 40 salary = 30000
name = madalam age = 79 salary = 100000

升级:如何调用子类特有方法,比如Teacher有一个teach,Student有一个study怎么调用?

 for (Person p:people
             ) {
            System.out.println(p.say());

            if (p instanceof Student)
                ((Student) p).study();
            else if (p instanceof Teacher)
                ((Teacher) p).teach();
        }

结果

name = amei age = 21 score = 90
ameiis studying…

name = aha age = 20
name = marry age = 30 score = 89
marryis studying…

name = socro age = 40 salary = 30000
socrois teaching…

name = madalam age = 79 salary = 100000
madalamis teaching…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值