用idea定义Employee类: 属性salary(工资) 定义salary的getter和setter 定义print,返回salary的值; 定义Manager为Employee的子类: 定义属性allowance(津贴) 定义构造方法,用参数给salary和allowance赋值。 重写print方法,返回salary与allowance的和。 在Demo类中编写main方法,声明Employee类的对象p1,为其创建Employee对象,设置salary为5000,声明Employee类的对象p2,为其创建Manager类对象,设置salary为6000,allowance为2000,分别调用p1和p2的print方法获取工资并返回。
时间: 2024-03-10 17:45:32 浏览: 107
好的,以下是代码实现:
Employee.java:
```java
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double print() {
return salary;
}
}
```
Manager.java:
```java
public class Manager extends Employee {
private double allowance;
public Manager(double salary, double allowance) {
setSalary(salary);
this.allowance = allowance;
}
@Override
public double print() {
return getSalary() + allowance;
}
}
```
Demo.java:
```java
public class Demo {
public static void main(String[] args) {
Employee p1 = new Employee();
p1.setSalary(5000);
System.out.println("p1的工资为:" + p1.print());
Manager p2 = new Manager(6000, 2000);
System.out.println("p2的工资为:" + p2.print());
}
}
```
输出结果:
```
p1的工资为:5000.0
p2的工资为:8000.0
```
阅读全文