用java编写用户类,包含属性 用户名,手机号码,家庭住址,密码 1.编写构造函数给成员属性赋值,同样需要参数名与属性名相同,使用this关键字 2.结合static关键字改写之前的构造函数,实现在每次创建新对象时能显示是第几个被创建的对象(添加一个静态的整形属性,每次在构造函数中对其加一并显示当前值) 3.结合static关键字实现,仅在第一次创建对象时显示:开始加载类文件。。。(静态块) 4.在测试类中测试上述要求
时间: 2024-02-12 12:04:39 浏览: 54
好的,我将逐一回答你的问题。
1. 用Java编写用户类,包含属性用户名,手机号码,家庭住址,密码。编写构造函数给成员属性赋值,同样需要参数名与属性名相同,使用this关键字:
```java
public class User {
private String username;
private String phoneNumber;
private String homeAddress;
private String password;
public User(String username, String phoneNumber, String homeAddress, String password) {
this.username = username;
this.phoneNumber = phoneNumber;
this.homeAddress = homeAddress;
this.password = password;
}
// Getters and setters...
}
```
2. 结合static关键字改写之前的构造函数,实现在每次创建新对象时能显示是第几个被创建的对象(添加一个静态的整型属性,每次在构造函数中对其加一并显示当前值):
```java
public class User {
private String username;
private String phoneNumber;
private String homeAddress;
private String password;
private static int count = 0;
public User(String username, String phoneNumber, String homeAddress, String password) {
this.username = username;
this.phoneNumber = phoneNumber;
this.homeAddress = homeAddress;
this.password = password;
count++;
System.out.println("第" + count + "个用户被创建");
}
// Getters and setters...
}
```
3. 结合static关键字实现,仅在第一次创建对象时显示:“开始加载类文件。。。”(静态块):
```java
public class User {
private String username;
private String phoneNumber;
private String homeAddress;
private String password;
private static int count = 0;
static {
System.out.println("开始加载类文件。。。");
}
public User(String username, String phoneNumber, String homeAddress, String password) {
this.username = username;
this.phoneNumber = phoneNumber;
this.homeAddress = homeAddress;
this.password = password;
count++;
System.out.println("第" + count + "个用户被创建");
}
// Getters and setters...
}
```
4. 在测试类中测试上述要求:
```java
public class UserTest {
public static void main(String[] args) {
User user1 = new User("Tom", "123456789", "北京市朝阳区", "123456");
User user2 = new User("Jerry", "987654321", "上海市浦东新区", "123456");
}
}
```
输出结果如下:
```
开始加载类文件。。。
第1个用户被创建
第2个用户被创建
```
阅读全文