The getClass() method in Java is used to obtain the runtime class of an object. It is defined in the Object class and returns a Class object that represents the class of the object.
In this chapter, you will learn about the Java getClass() method, its syntax, return value, and how to use it to obtain information about an object's runtime class.
The getClass() method is a method of the Object class that returns the runtime class of an object. Since every Java class directly or indirectly inherits from Object, the method can be called on objects of any class.
The syntax of object.getClass() method is as follows:
object.getClass()
The method does not accept any arguments and returns a Class<?> object representing the runtime class of the object.
In the following example, we use the getClass() method to obtain the runtime class of a Student object.
Java
class Student {
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.getClass());
}
}
Output:
class Student
The getClass() method returns a Class object, which provides methods such as getName() to obtain the fully qualified name of the class.
In the following example, we use getClass().getName() to get the fully qualified name of the class of an object.
Java
class Student {
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.getClass().getName());
}
}
Output:
Student
The getClass() method returns the actual runtime class of an object, not the type of the reference variable used to refer to the object.
In the following example, we use a superclass reference to refer to a Dog object and use getClass() to determine its runtime class.
Java
class Animal {
}
class Dog extends Animal {
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
System.out.println(animal.getClass().getName());
}
}
Output:
Dog
The getClass() method and the instanceof operator can both be used to check the type of an object, but they work differently.
| getClass() | instanceof |
|---|---|
| Returns a Class object representing the runtime class | Checks whether an object belongs to a specified type |
| Can be used to obtain class information | Returns true or false |
| Identifies the exact runtime class | Can also return true for a superclass or interface |
| Example: obj.getClass() | Example: obj instanceof Animal |
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India