The getClass()
method can be used to find the runtime class type of an object. See the example below:
public class User {
private long userID;
private String name;
public User(long userID, String name) {
this.userID = userID;
this.name = name;
}
}
public class SpecificUser extends User {
private String specificUserID;
public SpecificUser(String specificUserID, long userID, String name) {
super(userID, name);
this.specificUserID = specificUserID;
}
}
public static void main(String[] args){
User user = new User(879745, "John");
SpecificUser specificUser = new SpecificUser("1AAAA", 877777, "Jim");
User anotherSpecificUser = new SpecificUser("1BBBB", 812345, "Jenny");
System.out.println(user.getClass()); //Prints "class User"
System.out.println(specificUser.getClass()); //Prints "class SpecificUser"
System.out.println(anotherSpecificUser.getClass()); //Prints "class SpecificUser"
}
The getClass()
method will return the most specific class type, which is why when getClass()
is called on anotherSpecificUser
, the return value is class SpecificUser
because that is lower down the inheritance tree than User
.
It is noteworthy that, while the getClass
method is declared as:
public final native Class<?> getClass();
The actual static type returned by a call to getClass
is Class<? extends T>
where T
is the static type of the object on which getClass
is called.
i.e. the following will compile:
Class<? extends String> cls = "".getClass();