When can we use the getClass() method in Java?


The getClass() method is from Object class and it returns an instance of the Class class. When we declare a new instance of an object, it will be referring to a class. There can only be one class per JVM but multiple object referring to it. So when we get the class of two objects, they might be referring to the same class.

Syntax

public final Class<?> getClass()

Example

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());
   }
}

Output

class User
class SpecificUser
class SpecificUser
raja
Published on 11-Sep-2019 18:27:11
Advertisements