我们能从 java 中的方法返回此关键字吗?
Java 中的“this” 关键字用作对实例方法或构造函数中的当前对象的引用。使用 this,您可以引用类的成员,例如构造函数、变量和方法。

返回“this”
是的,您可以在 Java 中返回 this,即以下语句有效。
return this;
当您从某个方法返回 “this” 时,将返回当前对象。
范例
在以下 Java 范例中,Student 类有两个私有变量:name 和 age。从 setValues() 方法中,我们将从用户那里读取值并将其分配给这些(实例)变量,同时返回当前对象。
public class Student {
private String name;
private int age;
public Student SetValues(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
this.name = name;
this.age = age;
return this;
}
public void display() {
System.out.println("name: "+name);
System.out.println("age: "+age);
}
public static void main(String args[]) {
Student obj = new Student();
obj = obj.SettingValues();
obj.display();
}
}输出
Enter the name of the student: Krishna Kasyap Enter the age of the student: 21 name: Krishna Kasyap age: 21
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP