Javase易混点专项复习01_this关键字
- 1.this关键字
- 1.1功能:
- 1.1.1表示当前对象
- 1.1.2 表示构造方法;
- 1.2内存解释:
1.this关键字
1.1功能:
表示当前对象;
表示构造方法;
1.1.1表示当前对象
this可以用来指代当前对象,当成员变量和局部变量重名,可以用关键字this来区分。
- 当方法参数与成员变量同名时,必须使用this明确指定访问的是成员变量。
this点出来的一定是成员的变量
哪个对象调用的this所在的方法,this就代表哪个对象
public class Student {private String name; // 成员变量public void setName(String name) { // 参数与成员变量同名this.name = name; // this.name指向成员变量}
}
1.1.2 表示构造方法;
- 调用本类其他构造方法
通过this(参数)在构造方法中调用同一类的其他构造方法
注意:this(参数)必须在构造方法的第一行。
public class ChangFangXing {private int width, height;public ChangFangXing() {this(10, 10); // 调用全参构造方法}public RChangFangXing(int width, int height) {this.width = width;this.height = height;}
}
1.2内存解释:
public class Person {String name;/*哪个对象调用的this所在的方法,this就代表哪个对象*/public void speak(String name){System.out.println(this+"........");System.out.println(this.name+"您好,我是"+name);}
}
public class Test01 {public static void main(String[] args) {Person person = new Person();System.out.println(person+"=========");person.name = "沉香";person.speak("刘彦昌");System.out.println("==========");Person person2 = new Person();System.out.println(person2+"+++++");person2.name = "奥特曼";person2.speak("奥特曼之父");}
}
public class Person {private String name;private int age;//为name提供get/set方法public void setName(String name) {this.name = name;}public String getName() {return name;}//为age提供get/set方法public void setAge(int age) {this.age = age;}public int getAge() {return age;}
}
public class Test01 {public static void main(String[] args) {Person person = new Person();person.setName("因顺于");person.setAge(16);System.out.println(person.getName()+"..."+person.getAge());}
}