public class User {
int id;
String name; //用户名
String pwd; //密码
User(){
}
public User(int _id){
id = _id;
}
public User(int _id,String _name,String _pwd){
id = _id;
name = _name;
pwd = _pwd;
}
public static void main(String[] args) {
User u1 = new User();
User u2 = new User(1001);
User u3 = new User(1002,"张三","123456");
}
}
this的本质是什么?【简答】
this的本质就是“当前对象的地址”。普通方法中,this总是指向调用该方法的对象。构造方法中,this总是指向正要初始化的对象。
/**
* this的用法测试
*/
public class User2 {
int id;
String name;
String pwd;
public User2(){
}
public User2(int id,String name) {
System.out.println("正在要初始化的对象:"+this);
this.id = id;
this.name = name;
}
public User2(int id,String name,String pwd) {
this(id,name); //调用了重载的构造器!这种调用,必须位于构造方法的第一行!
this.pwd = pwd;
}
public void login(){
System.out.println("账户名:"+this.name+",密码:"+this.pwd);
}
public static void main(String[] args) {
User2 u = new User2(1001,"张三");
u.login();
User2 u3 = new User2(1002,"李四","123456");
System.out.println(u3.pwd);
System.out.println(u3.name);
}
}