There are many times when we may need to know the class name of the object being used. Example :- If we are iterating a list of different objects and we need to know the class name of the objects.
To know the class name we use objectName.getClass().getName()
Let us look at an example code:
public class Tech4Humans {
public static void main(String[] args) {
DummyClass dum=new DummyClass();
// using object name(dum) to get class name
System.out.println(dum.getClass().getName());
dum.test();
}
}
class DummyClass{
int num;
String str;
void test() {
// to get current class name we use this keyword
System.out.println("My class name is = "+this.getClass().getName());
}
}
Output
DummyClass
My class name is = DummyClass
You can see in the above code that to get a class name we are using object name(dum) to access the getClass().getName() method. Also to get current class name we use this keyword.