用java定义一个person类,属性有姓名,性别,年龄,住址,工作单位,工资 点击复制后,将打开C知道体验页功能方法,修姓名和年龄,修改地址,要求对所有构造方法和功能方法进行测试
时间: 2023-05-18 10:05:27 浏览: 74
java代码-使用java构造Person类。包括姓名(name),性别和年龄(age)的源代码
5星 · 资源好评率100%
以下是使用Java定义的Person类,包含姓名、性别、年龄、住址、工作单位和工资属性,以及相应的构造方法和功能方法:
```java
public class Person {
private String name;
private String gender;
private int age;
private String address;
private String company;
private double salary;
public Person(String name, String gender, int age, String address, String company, double salary) {
this.name = name;
this.gender = gender;
this.age = age;
this.address = address;
this.company = company;
this.salary = salary;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
System.out.println("Company: " + company);
System.out.println("Salary: " + salary);
}
}
```
下面是对所有构造方法和功能方法进行测试的示例代码:
```java
public class TestPerson {
public static void main(String[] args) {
// 测试构造方法1
Person person1 = new Person("张三", "男", 25, "北京市朝阳区", "ABC公司", 5000.0);
person1.printInfo();
// 测试构造方法2
Person person2 = new Person("李四", 30);
person2.setGender("女");
person2.setAddress("上海市浦东新区");
person2.setCompany("XYZ公司");
person2.setSalary(8000.0);
person2.printInfo();
}
}
```
运行结果如下:
```
Name: 张三
Gender: 男
Age: 25
Address: 北京市朝阳区
Company: ABC公司
Salary: 5000.0
Name: 李四
Gender: 女
Age: 30
Address: 上海市浦东新区
Company: XYZ公司
Salary: 8000.0
```
阅读全文