Java 中关键字 this 的所有用法有哪些?

java 8object oriented programmingprogramming

您可以使用 this 关键字来 –

  • 在构造函数或方法中,如果实例变量与局部变量同名,则将其区分开来。
class Student {
   int age;
   Student(int age) {
      this.age = age;
   }
}
  • 在类中调用一种类型的构造函数(参数化构造函数或默认构造函数)。这称为显式构造函数调用。
class Student {
   int age
   Student() {
      this(20);
   }
   Student(int age) {
      this.age = age;
   }
}

相关文章