Home > Java > javaTutorial > body text

In Java, when can we use getClass() method?

WBOY
Release: 2023-08-27 13:17:16
forward
727 people have browsed it

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.

Syntax

public final Class<?><!--?--> getClass()
Copy after login

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

Output

class User
class SpecificUser
class SpecificUser
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!