Exercise:
Write a Java Program to determine the class of an object.
1.Check using getClass()
Click Here to View the Solution!
//Declaring 2 Classes
class First {
}
class Second {
}
public class Main {
public static void main(String[] args) {
// create objects
First obj1 = new First ();
Second obj2 = new Second();
// get the class of the objects
System.out.print("The class of obj1 is: ");
System.out.println(obj1.getClass());
System.out.print("The class of obj2 is: ");
System.out.println(obj2.getClass());
}
}
Click Here to View the Output!
The class of obj1 is: class First The class of obj2 is: class Second
Click Here to View the Explanation!
- This program is used to find the class of an object by using the
getClass()
method. - Initially, two classes
First
andSecond
are initialized without any body. - In the
Main
class, two objectsobj1
andobj2
are created of these two classes. - Now, to get the classes of these objects, a
getClass()
method of the class Object is used as follows:obj1.getClass() and obj2.getClass()
.
- Finally, the output of the both the methods are printed that will display the class of each object.
2.Check using instanceOf operator
Click Here to View the Solution!
class TestClass {
//created class to pass as parameter
}
public class Main {
public static void main(String[] args) {
TestClass obj = new TestClass();
// check if obj is an object of Test
if(obj instanceof TestClass) {
System.out.println("obj is an object of the Test class");
}
else {
System.out.println("obj is not an object of the Test class");
}
}
}
Click Here to View the Output!
obj is an object of the Test class
Click Here to View the Explanation!
- This program is used to find the class of an object by using an operator
instanceOf
. - Initially, a class
TestClass
is created without any body. - In the
Main
class, an objectobj
of the classTestClass
is created. - Now, to check whether
obj
is an instance of the classTestClass
, an operatorinstanceOf
is used inside anif..else
statement as follows: (obj instanceOf TestClass
). - If the condition is true, then the message “obj is an instance of the class Test Class” is printed. Else, “obj is not an instance of the class Test Class”.