文章目录
- this关键字
- 基本作用
- 调用变量
- 调用方法
- 调用构造器
- this 关键字的限制
this关键字
- 它在方法(实例方法或非 static 的方法)内部使用,表示调用该方法的对象
- 它在构造器内部使用,表示该构造器正在初始化的对象。
基本作用
- 引用当前对象:在类的方法内部,this 可以用来引用当前对象。这是非常重要的,因为在面向对象编程中,一个类的方法通常会被多个对象调用。使用 this 关键字可以确保你正在操作的是调用方法的那个对象。
- 区分成员变量和方法参数:有时,方法的参数名与成员变量名相同,这可能导致混淆。this 可以帮助我们明确指定操作的是成员变量还是方法参数,提高代码的可读性。
调用变量
this
可以用来引用当前对象的成员变量 ,this.name 表示当前对象的 name 成员变量,而 name 表示方法参数。使用 this 可以清晰地区分两者,避免歧义。
public class Person {String name;public void setName(String name) {this.name = name;}
}
调用方法
class Person{private String name ;private int age ;public Person(String name,int age){this.name = name ; this.age = age ; }public void setName(String name){this.name = name;}public void setAge(int age){this.age = age;}public void getInfo(){System.out.println("姓名:" + name) ;this.speak();}public void speak(){System.out.println(“年龄:” + this.age);}
}
调用构造器
this 可以作为一个类中构造器相互调用的特殊格式。
this():调用本类的无参构造器
this(实参列表):调用本类的有参构造器
public class Student {private String name;private int age;// 无参构造public Student() {// this("",18);//调用本类有参构造器}// 有参构造public Student(String name) {this();//调用本类无参构造器this.name = name;}// 有参构造public Student(String name,int age){this(name);//调用本类中有一个 String 参数的构造器this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getInfo(){return "姓名:" + name +",年龄:" + age;}}
this 关键字的限制
尽管 this 非常有用,但有一些限制和注意事项:
- this 不能在静态方法中使用,因为静态方法不属于任何特定对象,而是属于整个类。
- this 只能在方法内部使用,无法在方法外部使用。
- 在构造方法中,this 的调用必须作为构造方法的第一条语句。同时使用 this 和 super 关键字在同一个构造方法中是不允许的。