我们能否在 Java 中使用 this 关键字调用方法?
在 Java 中,用作当前对象的引用的 "this" 关键字存在于实例方法或构造函数中。是的,你可以使用它调用方法。但是,你应该仅从实例方法(非静态)调用它们。
举例说明
在以下示例中,Student 类有一个私有变量 name,带有 setter 和 getter 方法,使用 setter 方法,我们为 main 方法中的 name 变量赋予值,然后,我们在实例方法中使用"this"关键字调用 getter (getName) 方法。
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP