[英]Which variables constructor can access in Java class?
我正在研究 Java (OOP) 中的構造函數,但無法弄清楚構造函數可以訪問什么類型的變量? 構造函數可以訪問以下哪些變量?
我創建了以下示例來詳細說明我的問題:
public class constructorAccess {
public int marks; // 3. Public instance variable
private String firstName; // 2. Private instance variable
static final String LASTNAME = "Smith"; // 4. Static variable
public static void studentId(){
int id; // 1. Local variable inside method
id = 5;
System.out.println(id);
}
public constructorAccess(int marks, String firstName) {
this.marks = marks;
this.firstName = firstName;
}
}
是否可以從constructorAccess訪問id
(1.在studentId方法中聲明的局部變量)和LASTNAME
(4.在類中聲明的靜態變量)?
public constructorAccess(int marks, String firstName) {
this.marks = marks;
this.firstName = firstName;
// How can I use id variable here from studentId method?
// How can I use LASTNAME static variable here?
}
我用這個訪問了私有和公共實例變量。 引用但LASTNAME
和id
變量給了我錯誤(創建一個局部變量)。
局部變量只能被聲明局部變量的范圍內的代碼訪問(即,一對{
... }
)。 從方法外部訪問它們是沒有意義的,因為局部變量的存在與特定的方法調用相關聯:雖然該方法當前沒有被執行,但它的局部變量根本不存在; 如果該方法遞歸調用自身或從多個線程執行,則每個方法調用都有自己獨立的局部變量集。
對於您的其他三個問題:是的,如果構造函數(和方法)在同一個類中聲明,則它們始終可以訪問任何實例和靜態變量。 如果它們在不同的類中,則會出現更復雜的訪問規則。
如果您在分配給LASTNAME
的示例中收到錯誤,因為您將其聲明為final
,這意味着該變量只能分配給一次,並且由於它的值已經分配,您不能再次分配給它。 但它仍然是“可訪問的”,因為您可以讀取它的值。 或者使它成為static
non- final
,然后您可以讀取和分配給它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.