如何在 Java 中使用 this 关键字?
java 8object oriented programmingprogramming
Java 中的 this 关键字主要用于引用类的当前实例变量。它也可以用于隐式调用方法或调用当前类的构造函数。
以下程序演示了 Java 中 this 关键字的使用:
示例
class Student { private int rno; private String name; public Student(int rno, String name) { this.rno = rno; this.name = name; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } } public class Demo { public static void main(String[] args) { Student s = new Student(105, "Peter Bones"); s.display(); } }
输出
Roll Number: 105 Name: Peter Bones
现在让我们理解一下上面的程序。
Student 类创建时包含数据成员 rno 和 name。构造函数 Student() 使用 this 关键字初始化 rno 和 name,以区分同名的局部变量和实例变量。成员函数 display() 显示 rno 和 name 的值。以下代码片段演示了这一点:
class Student { private int rno; private String name; public Student(int rno, String name) { this.rno = rno; this.name = name; } public void display() { System.out.println(&"Roll Number: &" + rno); System.out.println(&"Name: &" + name); } }
在 main() 方法中,创建 Student 类的一个对象 s,其值为 105 和"Peter Bones"。然后调用 display() 方法。以下代码片段演示了此过程:
public class Demo { public static void main(String[] args) { Student s = new Student(105, "Peter Bones"); s.display(); } }