Java中的“ this”关键字在实例方法或构造函数中用作对当前对象的引用。是的,您可以使用它来调用方法。但是,您只能从实例方法(非静态)中调用它们。
在下面的示例中,Student类具有一个私有变量名称,具有setter和getter方法,使用setter方法,我们已从main方法向name变量分配了值,然后,我们使用“实例方法中的“ this”关键字。
public class ThisExample_Method {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("name: "+this.getName());
}
public static void main(String args[]) {
ThisExample_Method obj = new ThisExample_Method();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
obj.setName(name);
obj.display();
}
}输出结果
Enter the name of the student: Krishna name: Krishna