用JAVA完成 设置一个表示用户的User类。类的属性有用户名、密码和用户个数;类有3个构造方法(无参、为用户名赋值、为用户名和密码赋值)、获取和设置用户名和密码的方法,以及获取用户个数的方法,并编写
首先,我们需要创建一个User类,包含用户名、密码和用户个数属性。然后,我们需要为这个类创建3个构造方法,分别是无参构造方法、为用户名赋值的构造方法和为用户名和密码赋值的构造方法。接下来,我们需要为这个类创建获取和设置用户名和密码的方法,以及获取用户个数的方法。最后,我们需要编写一个测试程序,分别调用这3个方法并打印出用户名、密码及用户数信息。
以下是代码实现:
```java
public class User {
private String username;
private String password;
private static int userCount = 0;
public User() {
userCount++;
}
public User(String username) {
this.username = username;
userCount++;
}
public User(String username, String password) {
this.username = username;
this.password = password;
userCount++;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static int getUserCount() {
return userCount;
}
}
public class Test {
public static void main(String[] args) {
User user1 = new User();
User user2 = new User("张三");
User user3 = new User("李四", "123456");
System.out.println("用户名:" + user1.getUsername());
System.out.println("密码:" + user1.getPassword());
System.out.println("用户个数:" + User.getUserCount());
System.out.println("用户名:" + user2.getUsername());
System.out.println("密码:" + user2.getPassword());
System.out.println("用户个数:" + User.getUserCount());
System.out.println("用户名:" + user3.getUsername());
System.out.println("密码:" + user3.getPassword());
System.out.println("用户个数:" + User.getUserCount());
}
}
```
运行上述测试程序,将会输出以下结果:
```
用户名:null
密码:null
用户个数:1
用户名:张三
密码:null
用户个数:2
用户名:李四
密码:123456
用户个数:3
```
以下是代码实现:
```java
public class User {
private String username;
private String password;
private static int userCount = 0;
public User() {
userCount++;
}
public User(String username) {
this.username = username;
userCount++;
}
public User(String username, String password) {
this.username = username;
this.password = password;
userCount++;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static int getUserCount() {
return userCount;
}
}
public class Test {
public static void main(String[] args) {
User user1 = new User();
User user2 = new User("张三");
User user3 = new User("李四", "123456");
System.out.println("用户名:" + user1.getUsername());
System.out.println("密码:" + user1.getPassword());
System.out.println("用户个数:" + User.getUserCount());
System.out.println("用户名:" + user2.getUsername());
System.out.println("密码:" + user2.getPassword());
System.out.println("用户个数:" + User.getUserCount());
System.out.println("用户名:" + user3.getUsername());
System.out.println("密码:" + user3.getPassword());
System.out.println("用户个数:" + User.getUserCount());
}
}
```
运行上述测试程序,将会输出以下结果:
```
用户名:null
密码:null
用户个数:1
用户名:张三
密码:null
用户个数:2
用户名:李四
密码:123456
用户个数:3
```