目录
this 在实例方法中使用,代表当前对象。
this 在构造方法中调用其他构造方法,必须在构造方法第一行。
格式: this.
- public class Person {
-
- private String name;
- private int age;
-
- public Person(String name, int age) { // 构造方法
- this.name = name; // this 代表当前对象
- this.age = age; // this 代表当前对象
-
- //name = name; // 省略this写法
- //age = age; // 省略this写法
- }
-
- public void say() { // 普通方法
- System.out.println("name ="+this.name+" age="+this.age); // this代表当前对象
- System.out.println("name ="+name+" age="+age); // 省略this写法
- }
-
- public static void main(String[] args) {
- Person person = new Person("张三", 18);
- person.say();
-
- }
-
- }
语法: this (实参)
- public class Person {
-
- private String name;
- private int age;
-
-
-
- public Person(String name) {// 构造方法
- this.name = name;
- }
-
- public Person(String name, int age) { // 构造方法
- this(name); // 调用其他构造方法必须放在第一行,不然编译不通过
- this.age = age;
- }
-
- public void say() { // 普通方法
- System.out.println("name ="+this.name+" age="+this.age); // this代表当前对象
- }
-
- public static void main(String[] args) {
- Person person = new Person("张三", 18);
- person.say();
-
- }
-
- }
this 不能使用在带有 static 的方法当中。因为 this 表示当前对象,所属对象,而被 static 修饰方法所属类,对象的产生是先有类。