getClass() 方法來自 Object 類,它會傳回一個Class 類別的實例。當我們聲明一個物件的新實例時,它將引用一個類別。每個 JVM 只能有一個類,但有多個物件引用它。因此,當我們取得兩個物件的類別時,它們可能引用同一個類別。
public final Class<?><!--?--> getClass()
class User { private int id; private String name; public User(int id, String name) { this.id = id; this.name = name; } } class SpecificUser extends User { private String specificId; public SpecificUser(String specificId, int id, String name) { super(id, name); this.specificId = specificId; } } public class TestUser { public static void main(String[] args){ User user = new User(115, "Raja"); SpecificUser specificUser = new SpecificUser("AAA", 120, "Adithya"); User anotherSpecificUser = new SpecificUser("BBB", 125, "Jai"); System.out.println(user.getClass()); System.out.println(specificUser.getClass()); System.out.println(anotherSpecificUser.getClass()); } }
class User class SpecificUser class SpecificUser
以上是在Java中,我們什麼時候可以使用getClass()方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!