(1)写一个基类Employee,有一个非静态方法void computePay()和一个静态方法expenseAllowance()。computePay只需要打印字符串表示自己是Employee类的computePay方法即可;expenseAllowance只需要打印字符串表示自己是Employee类的expenseAllowance方法即可。 (2)写一个类Manager派生自Employee,覆盖了父类的computePay()和expenseAllowance()方法。computePay只需要打印字符串表示自己是Manager类的computePay方法即可;expenseAllowance只需要打印字符串表示自己是Manager类的expenseAllowance方法即可。 写一个类TestEmp,在main函数中声明一个Employee的对象emp,一个Manager类型的对象man。并将man向上塑性为Employee类型的引用变量emp2。分别调用emp. computePay(), man. computePay(), emp2. computePay()以及emp. expenseAllowance (), man. expenseAllowance (), emp2. expenseAllowance()。
时间: 2024-02-15 21:04:48 浏览: 78
上海交大网络面向对象程序设计Java第一、二、三次作业答案.doc
代码如下:
```java
class Employee {
public void computePay() {
System.out.println("This is Employee's computePay method");
}
public static void expenseAllowance() {
System.out.println("This is Employee's expenseAllowance method");
}
}
class Manager extends Employee {
@Override
public void computePay() {
System.out.println("This is Manager's computePay method");
}
@Override
public static void expenseAllowance() {
System.out.println("This is Manager's expenseAllowance method");
}
}
public class TestEmp {
public static void main(String[] args) {
Employee emp = new Employee();
Manager man = new Manager();
Employee emp2 = man;
emp.computePay();
man.computePay();
emp2.computePay();
emp.expenseAllowance();
man.expenseAllowance();
emp2.expenseAllowance();
}
}
```
输出结果为:
```
This is Employee's computePay method
This is Manager's computePay method
This is Manager's computePay method
This is Employee's expenseAllowance method
This is Manager's expenseAllowance method
This is Employee's expenseAllowance method
```
可以看到,调用同名方法时,子类方法会覆盖父类方法,但静态方法不会发生重写,只会隐藏父类方法。使用向上转型后,被引用的变量只能调用其类型或其父类中定义的方法。
阅读全文