我们可以在Java中使用此关键字调用方法吗?
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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短