getClass method

suggest change

The getClass() method can be used to find the runtime class type of an object. See the example below:

class User {
    private long userID;
    private String name;

    public User(long userID, String name) {
        this.userID = userID;
        this.name = name;
    }
}

class SpecificUser extends User {
    private String specificUserID;

    public SpecificUser(String specificUserID, long userID, String name) {
        super(userID, name);
        this.specificUserID = specificUserID;
    }
}

public class Main {
    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"
    }
}

Two public top-level classes cannot share one file, and main has to be inside a class. The classes above are package-private so this example can live in Main.java. Class.toString() prints class plus the binary name, so a package would show up in that text.

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.

The following compiles:

Class<? extends String> cls = "".getClass();

For a parameterized receiver the bound is the erasure. List<String> names gives Class<? extends List>, not Class<? extends List<String>>.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents