程序示例
抽象父类 – People,分别定义好姓名,年龄以及家庭住址以及全参构造器
abstract class People {
public String name;
public int age;
public String address;
People(String name , int age , String address) {
this.name = name;
this.age = age;
this.address = address;
}
下分三个子类分别继承于People类,子类的构造函数中会自动调用父类的构造函数,由于父类当中已经定义好了有参构造器, 系统不再提供默认无参构造器给父类,此时子类需使用super关键字用于从子类中调用父类的构造方法,成员变量或者成员方法。
class Student extends People { //学生类
private double freeMoney;
Student(String name , int age , String address , double freeMoney) {
super(name , age , address );
this.freeMoney = freeMoney;
}
public void show() { //重写父类当中的抽象方法
System.out.println("名字是:" + name + " 年龄是:" + age + " 地址是:" +
" 现在有" + freeMoney + "元零花钱");
}
}
class Singer extends People { //歌手类
private double salary;
Singer(String name , int age , String address , double salary) {
super(name , age , address );
this.salary = salary;
}
public void show() { //重写父类当中的抽象方法
System.out.println("名字是:" + name + " 年龄是:" + age + " 地址是:"
+ address + " 一个月有" + salary + "元工资");
}
}
class Doctor extends People{ //医生类
private short num;
Doctor(String name , int age , String address , short num){
super(name , age , address);
this.num = num;
}
public void show() { //重写父类当中的抽象方法
System.out.println("名字是:" + name + " 年龄是:" + age + " 地址是:" + address +
" 我一天要接待" + num + "名病人");
}
}
主类PeopleTest类
父类引用指向子类的对象,People分别向上转型创建三种对象Student、Doctor、Singer,并且分别调用其重写好的show()方法
public class PeopleTest{
public static void main(String[] args) {
People[] p = new People[3];
//多态的体现
p[0] = new Student("小学生" , 12 , "0路" , 1000);
p[1] = new Singer("一位不知名的歌手",22,"3路",3000);
p[2] = new Doctor("张医生" , 35 , "4路" , (short) 2);
for (int i = 0; i < p.length; i++) {
p[i].show();
}
}
}