1
Sponsored Links


Ad by Google
getClass(): getClass method of java.lang.Object class is a final method means you cannot override the getClass method. Sometimes interviewer ask you to override the getClass method just to confuse you.
But don't be confused all the method of Object class cannot be override except toString(),equals(Object o),hashCode(),clone() and finalize() once again getClass() is a final method of Object class and you cannot override the final methods. getClass method return the runtime class of the object which has method called. By using getClass method you will get the full information about the class such as number of methods in your class declared using getClass().getMethods() which will return you the array of methods, number of interfaces implemented by your class using getClass().getInterfaces() In nutshell you will get the whole information about your class using getClass() method. For example the below class is going to display you the number of methods,fields declared in Product.java and also number of interfaces implemented by Product class.

package com.javamakeuse.test;

public class Product implements ProductInterface {

 private String name;
 private double price;
 private String manufacturer;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 @Override
 public String toString() {
  return "Product [name=" + name + ", price=" + price + ", manufacturer="
    + manufacturer + "]";
 }
 
 public static void main(String[] args) {
  
  Product product = new Product();
  
  System.out.println("Fully qualified class name=> "+product.getClass());
  System.out.println("Number of Interfaces implemented=> "+product.getClass().getInterfaces().length);
  System.out.println("Number of Methods declared=> "+product.getClass().getDeclaredMethods().length);
  System.out.println("Number of Fields=> "+product.getClass().getDeclaredFields().length);
 }

}

Out Put:
Fully qualified class name=> class com.javamakeuse.test.Product
Number of Interfaces implemented=> 1
Number of Methods declared=> 4
Number of Fields=> 3

About 60 methods are there to get you the information of your class few most popular methods are:
getClass().getSimpleName()
getClass().getClassLoader()
getClass().getAnnotations()
getClass().isAnnotation()
getClass().getDeclaredConstructors()
getClass().isEnum()

Mostly getClass() method used while playing with reflection.

Sponsored Links

1 comments:

  1. Hello sir,

    I would like to request you to write about Enum.

    ReplyDelete