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中文网其他相关文章!