阿里网站官网入口,最新的网络营销手段,镇江整站优化,培训型网站建设this
在Java中#xff0c;this 是一个特殊的引用变量#xff0c;它引用了当前对象实例。当在类的非静态方法或构造方法中使用时#xff0c;this 关键字指代当前的对象实例。它经常用于区分对象的成员变量和局部变量#xff0c;或者调用其他重载的方法。
以下是一些使用 t…this
在Java中this 是一个特殊的引用变量它引用了当前对象实例。当在类的非静态方法或构造方法中使用时this 关键字指代当前的对象实例。它经常用于区分对象的成员变量和局部变量或者调用其他重载的方法。
以下是一些使用 this 关键字的示例
引用对象的成员变量 当一个局部变量与一个成员变量同名时可以使用 this 来引用成员变量。
public class Person { private String name; public Person(String name) { this.name name; } public String getName() { return name; } public void setName(String name) { this.name name; }
}测试
public class PersonTest { public static void main(String[] args) { Person person new Person(Alice); System.out.println(person.getName()); // 输出: Alice person.setName(Bob); System.out.println(person.getName()); // 输出: Bob }
}调用同一类中的其他方法 可以使用 this 来调用同一类中的其他方法。
public class MyClass {public void method1() {System.out.println(Method 1);this.method2(); // 使用this来调用method2()}public void method2() {System.out.println(Method 2);}
}测试
public class MyClassTest {public static void main(String[] args) {MyClass myClass new MyClass();myClass.method1();}
}在构造方法中引用当前对象 在构造方法中可以使用 this 来引用当前正在创建的对象。
public class Student {private String name;private int age;public Student(String name, int age) {this.name name; // 引用成员变量namethis.age age; // 引用成员变量age}public Student(String name) {this.name name; // 引用成员变量namethis.age 18; // 设置默认年龄为18}public String getName() {return name;}public int getAge() {return age;}
}注意this 只能用于类的非静态方法中。在静态方法中不能使用 this因为静态方法是类级别的而不是实例级别的。
测试
public class StudentTest {public static void main(String[] args) {Student student new Student(Alice, 20);System.out.println(student.getName()); // 输出: AliceSystem.out.println(student.getAge()); // 输出: 20}
}