定义一个Person类和它的子类Employee。Person类有姓名、年龄和电话号码等私有成员变量,为私有成员变量分别定义set和get方法;定义一个方法showMessage()输出Person类的成员变量。Employee类有部门、工资等私有成员变量,定义一个方法showMessage()输出Employee的基本信息(含姓名、年龄和电话号码)。Person类和Employee类均定义带参和不带参的构造方法实现对其成员变量的初始化。定义一个public类,在其main()方法中分别基于父类和子类创建两个对象,通过构造方法分别为父类和子类的成员变量赋值,然后分别调用父类和子类的showMessage()方法输出其基本信息。使用java编写
时间: 2023-02-09 17:46:32 浏览: 219
在 Java 中,可以使用如下代码定义 Person 类和 Employee 类:
```
public class Person {
private String name;
private int age;
private String phone;
public Person() {
// 默认构造方法
}
public Person(String name, int age, String phone) {
this.name = name;
this.age = age;
this.phone = phone;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
public void showMessage() {
System.out.println("姓名: " + name + ", 年龄: " + age + ", 电话: " + phone);
}
}
public class Employee extends Person {
private String department;
private double salary;
public Employee() {
// 默认构造方法
}
public Employee(String name, int age, String phone, String department, double salary) {
super(name, age, phone);
this.department = department;
this.salary = salary;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDepartment() {
return department;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void showMessage() {
super.showMessage();
System.out.println("部门: " + department + ", 工资: " + salary);
}
}
```
然后,可以在另一个 public 类中的 main 方法中创建 Person 类和 Employee 类的对象,并调用 showMessage 方法输出其基本信息:
```
public class Test {
public static void main(String[] args) {
Person p = new Person("张三", 25, "123456");
p.showMessage();
Employee e = new Employee("李四", 30, "654321", "市场部", 8000);
e.showMessage();
}
}
```
输出结果如下:
```
姓名: 张三, 年龄: 25, 电话: 123456
阅读全文