this关键字
关于java中的this关键字:
this表示当前对象:
this.属性 区别成员变量和局部变量
this.() 调用本类的某个方法
this() 表示调用本类构造方法,只能用在构造方法的第一行语句。
this关键字只能出现在非static修饰的代码中
1、this是一个引用,this是一个变量,this变量中保存了内存地址指向了自身,this存储在JVM堆内存中Java对象的内部。
2、创建100Java对象,每一个对象都有this,也就是说有100个不同的this。
3、this可以出现在“实例方法”当中,(this指向)代表当前正在执行这个动作的对象。(this代表当前的对象“张三”)。
重点:没有static关键字的方法称为“实例方法”。实例方法访问:“引用”。
重点:没有static关键字的变量称为“实例变量”。
注意:当一个行为/动作执行的过程当中是需要对象参与的,那么这个方法一定要定义为“实例方法”,不要带static关键字
public class Customer {
String name;
public Customer() {
}
public void shopping() {
System.out.println(this.name + "在购物!");
}
}
public class CustomerTest {
public static void main(String[] args) {
Customer c1 = new Customer();
c1.name = "张三";
c1.shopping();
Customer c2 = new Customer();
c2.name = "李四";
c2.shopping();
}
由于name是一个实例变量,所以这个name访问的时候一定是访问当前对象的name 此时this可以省略
public class ThisTest {
int num = 10;
public static void main(String[] args) {
Customer c1 = new Customer();
String name=c1.name = "张三";
System.out.println(name);
}
}
public class ThisTest {
public static void main(String[] args) {
doSome();
ThisTest tt = new ThisTest();
tt.doOther();
tt.run();
}
public static void doSome() {
System.out.println("Do Some!");
}
public void doOther() {
this.run();
this.doSome();
System.out.println("Do Other!");
}
public void run() {
this.doSome();
System.out.println("Run!");
}
}
在带有static的方法当中,不能“直接”访问实例变量和实例方法。(可以通过类名去访问)
实例变量和实例方法都需要对象的存在(new)。
而static方法当中是没有this的,也就是说当前对象是不存在的。自然也是无法直接访问当前对象的实例变量和实例方法。
在不带有static的方法中可以使用this关键字访问实例变量/实例方法
This什么情况下不能省略
public class User {
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
}
区分实例变量和局部变量的时候不省略this
public class Date {
private int year;
private int month;
private int day;
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public Date() {
this(1970,1,1);
}
可以在本类的构造器中使用this关键字调用构造器/普通方法
调用构造器的时候 this必须位于首行
当在构造器中调用普通方法 this位置任意
this可以传递参数 例如:this(1970,1,1)
另外 普通方法中不能调用构造方法 但可以在构造方法中使 用this关键字调用普通方法
总结
1.可以使用在实例方法当中,代表当前对象。this.方法名();
2.可以使用在构造方法当中,通过当前的构造方法调用其他的构造方法 this必须位于第一行 this(传入的参数)
3.注意:普通方法中不能调用构造器
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)