如何使用 Java 中的 this 關鍵字?
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
現在讓我們瞭解一下上面的程式。
使用資料成員 rno、name 建立 Student 類。建構函式 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() 方法中,使用值 105 和 "Peter Bones" 建立類 Student 的一個物件 s。然後呼叫 display() 方法。以下程式碼片段演示了這一點
public class Demo {
public static void main(String[] args) {
Student s = new Student(105, "Peter Bones");
s.display();
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP