定义员工类(父类)(name,int salary),无/有2参构造方法,printInfo方法(员工姓名:XX,员工工资为XX);定义经理类(double salary,部门)无/有3参构造方法,重载printinfo方法。分别创建父类和子类对象并给父类
时间: 2024-05-06 13:21:53 浏览: 88
和子类的属性赋值,调用printInfo方法和重载后的printInfo方法输出信息。
代码如下:
```java
// 定义员工类(父类)
class Employee {
private String name;
private int salary;
// 无参构造方法
public Employee() {
}
// 有参构造方法
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
// 打印员工信息
public void printInfo() {
System.out.println("员工姓名:" + name + ",员工工资为" + salary);
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
// 定义经理类(子类)
class Manager extends Employee {
private double salary;
private String department;
// 无参构造方法
public Manager() {
}
// 有参构造方法
public Manager(String name, int salary, double salary1, String department) {
super(name, salary);
this.salary = salary1;
this.department = department;
}
// 重载printInfo方法
public void printInfo() {
System.out.println("经理姓名:" + getName() + ",经理工资为" + salary + ",所在部门为" + department);
}
// getter和setter方法
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
public class Test {
public static void main(String[] args) {
// 创建父类对象并赋值
Employee employee = new Employee();
employee.setName("张三");
employee.setSalary(5000);
// 调用printInfo方法输出信息
employee.printInfo();
// 创建子类对象并赋值
Manager manager = new Manager();
manager.setName("李四");
manager.setSalary(8000);
manager.setSalary(10000);
manager.setDepartment("市场部");
// 调用printInfo方法输出信息
manager.printInfo();
}
}
```
输出结果:
```
员工姓名:张三,员工工资为5000
经理姓名:李四,经理工资为10000.0,所在部门为市场部
```
阅读全文