Home >Java >javaTutorial >In Java, when can we use getClass() method?
getClass() method comes from the Object class, which returns an instance of the Class class. When we declare a new instance of an object, it will refer to a class. There can be only one class per JVM, but multiple objects refer to it. Therefore, when we get the classes of two objects, they may refer to the same class.
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
The above is the detailed content of In Java, when can we use getClass() method?. For more information, please follow other related articles on the PHP Chinese website!