- 用static ,引入计数器案例
class User {
private String uid;
private String password;
private static int count = 0;
public User(){
this("NOID","mldn");
}
public User(String uid){
this(uid,"mldnjava");
}
public User(String uid,String password){
this.uid = uid;
this.password = password;
count++;
}
public static int getCount(){//--这里加上static,下面才可以不实例化,直接User.getCount来调用
return count;
}
// getter,setter 略
public String getInfo(){
return "用户名:" + this.uid + ",密码:" + this.password;
}
}
public class HelloWorld {
public static void main(String[] args){
User userA = new User();
User userB = new User("小强");
User userC = new User("大强","ican");
System.out.println(userA.getInfo());
System.out.println(userB.getInfo());
System.out.println(userC.getInfo());
System.out.println("已实例化用户个数:" + User.getCount());// 用户个数
}
}
- 结果:
用户名:NOID,密码:mldn
用户名:小强,密码:mldnjava
用户名:大强,密码:ican
已实例化用户个数:3
标签:uid,案例,面向对象,5.23,User,static,password,public,String
From: https://www.cnblogs.com/pansidong/p/17453087.html