我们可以从 Java 中的方法返回此关键字吗?
java 8object oriented programmingprogramming
Java 中的"this"关键字用作对当前对象的引用,在实例方法或构造函数中。使用 this,您可以引用类的成员,例如构造函数、变量和方法。
返回“this”
是的,您可以在 Java 中返回this,即以下语句有效。
return this;
当您从方法返回"this 时,将返回当前对象。
示例
在下面的 Java 示例中,Student 类有两个私有变量 name 和 age。从方法 setValues() 中,我们从 user 读取值并将它们分配给这些(实例)变量并返回当前对象。
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