课堂练习1:教材160页4.编程题
课堂练习2:大学里的学生(Student)需要交学费,而研究生(Graduate)作为学生比较特殊,除了需要交学费外,还可以获取一部分科研津贴,由学校(University)统一发放。此外,学校还需要发放教师(Teacher)的工资。
编写代码模拟上述场景:
1) 设计抽象类Student:
l 属性包括姓名(name)、学费(fee);
l 方法包括:
-构造方法Student(String name)
-抽象方法void setFee(int fee)
-抽象方法int getFee()
2) 定义一个接口Salary:包含一个方法int getSalary();
3) 定义一个研究生类Graduate,继承Student类且实现Salary接口:
l 新增属性:收入(salary)
l 方法包括:
- 构造方法Graduate(String name)
- 重写void setFee(int fee)
- 重写int getFee()
- 重写int getSalary(),研究生获得工资1500
- 新增方法boolean isLoan(),判断是否需要贷款(若收入小于学费则需贷款)
4) 定义一个教师类(Teacher):
l 属性包括:姓名(name)、收入(salary)
l 方法包括:
- 构造方法Teacher(String name)
- 重写int getSalary(),教师获得工资3000
5) 定义一个大学类(University),通过void payOff(Salary s)方法给研究生和教师发放并打印工资。
public interface Salary {
int getSalary();
}
public abstract class Student {
public String name;
public int fee;
public Student(String name) {
super();
this.name = name;
}
/*public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
*/
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
}
public class Graduate extends Student implements Salary{
int salary;
public Graduate(String name) {
super(name);
}
@Override
public int getSalary() {
// TODO Auto-generated method stub
return this.salary = 1500;
}
public void setFee(int fee){
this.fee = fee;
}
public int getFee(){
return fee;
}
boolean isLoan(){
if(salary>fee){
return false;
}
else{
return true;
}
}
}
public class Teacher implements Salary {
String name;
int salary;
public Teacher(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return this.salary = 3000;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
public class University {
void payOff(Salary s){
if(s instanceof Teacher){
s.getSalary();
}
else if(s instanceof Graduate){
s.getSalary();
}
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Graduate g = new Graduate("小亮");
g.setFee(1000);
University u = new University();
u.payOff(g);
System.out.println("是否需要贷款:"+g.isLoan());
Teacher t = new Teacher("大王");
u.payOff(t);
}
}