// 抽象类的应用
//定义抽象类
abstract class Asss {
private String name;
private int age;
// 构造方法作为传参用
public Asss(String name, int age) {
this.age = age;
this.name = name;
}
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 abstract void out();
}
// 定义一个类继承
class Students extends Asss {
// 子类私有属性,在最后将会用抽象函数将其打印
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
// 重写构造对象
public Students(String name, int age, int num) {
super(name, age);
this.num = num;
}
// 重写抽象方法,然后用其打印内容
public void out() {
System.out.println("姓名:" + getName() + ";年龄:" + getAge() + ";分数:" + getNum());
}
}
// 第二个子类
class Worker extends Asss {
// 子类自由属性
private int money;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
// 重写构造对象
public Worker(String name, int age, int money) {
super(name, age);
this.money = money;
}
// 重写抽象方法,然后用其打印内容
public void out() {
System.out.println("姓名:" + getName() + ";年龄:" + getAge() + ";工资:" + getMoney());
}
}
public class index15 {
public static void main(String[] args) {
// 实例化
Worker worker = new Worker("张三", 30, 7000);
// 调用抽象函数
worker.out();
// 实例化
Students students = new Students("张小三", 10, 80);
// 调用抽象函数
students.out();
// 打印结果为姓名:
// 姓名:张三;年龄:30;工资:7000
// 姓名:张小三;年龄:10;分数:80
}
}
在父类中定义了一个抽象方法,在子类中来调用。运用构造方法,来传递参数,在子类中重写添加子类的自由参数。
打印结果为:
姓名:张三;年龄:30;工资:7000
姓名:张小三;年龄:10;分数:80