4.8 this关键字
-
this的本质就是“创建好的对象的地址”! 由于在构造方法调用前,对象已经创建。因此,在构造方法中也可以使用this代表“当前对象” 。
-
this最常的用法:
(1)在程序中产生二义性之处,应使用this来指明当前对象;普通方法中,this总是指向调用该方法的对象。构造方法中,this总是指向正要初始化的对象。
(2)使用this关键字调用重载的构造方法,避免相同的初始化代码。但只能在构造方法中用,并且必须位于构造方法的第一句。
(3)this不能用于static方法中。 -
代码示例:
/**
* 构建方法
*
* @author 王立生
*
* 题目:构建类:用户;类包含:姓名,id,密码;需满足:三种构建方法
*/
public class User {
//设置内容
int id;
String name;
String passWord;
public User(){
}
public User(int id,String name){
System.out.println("正在初始化已经创建的文件:"+this);
this.id= id;
this.name = name;
}
public void login(){
System.out.println(this.name+"要登录");
}
public static void main(String[] args){
User u2=new User(123,"王立生");//给User内容赋值
u2.login(); //调用方法
System.out.println(u2);
}
}
4.9 static关键字
static修饰的成员变量和方法,从属于类。普通变量和方法从属于对象的。
静态语句里,不能使用非静态方法
静态语句里,只能调用静态成员变量
/**
* 测试static关键字的用法
* @author 高淇
*
*/
public class User2 {
int id; // id
String name; // 账户名
String pwd; // 密码
static String company = "北京尚学堂"; // 公司名称
public User2(int id, String name) {
this.id = id;
this.name = name;
}
public void login() {
printCompany();
System.out.println(company);
System.out.println("登录:" + name);
}
public static void printCompany() {
// login();//调用非静态成员,编译就会报错
System.out.println(company);
}
public static void main(String[] args) {
User2 u = new User2(101, "高小七");
User2.printCompany();
User2.company = "北京阿里爷爷";
User2.printCompany();
}
}
/*
* 左边 outline 解读:
* 绿白C表示:类
* 蓝色三角形表示:属性
* 蓝色三角+s表示:静态属性
* 绿点表示:方法
* 绿点+c表示:方法构造(constractor)
* 绿点+s表示:静态方法
*
*/