Java设计一个User类并封装对应的数据,例如可以定义如下成员变量{privateString name private double height private double salary }
时间: 2024-02-15 20:31:57 浏览: 69
很好,这是一个 Java 编程问题。下面是一个示例代码:
```
public class User {
private String name;
private double height;
private double salary;
public User(String name, double height, double salary) {
this.name = name;
this.height = height;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return this.height;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getSalary() {
return this.salary;
}
}
```
这个类包含了一个构造函数,用于创建一个实例,以及三个访问器方法,用于读取和修改成员变量。你可以使用下面的代码来创建一个 User 对象:
```
User user = new User("John", 1.75, 5000.0);
```
然后,你可以通过调用访问器方法来访问成员变量的值,例如:
```
String name = user.getName();
double height = user.getHeight();
double salary = user.getSalary();
```
阅读全文