Write a Java Program to Determine the class of an object

Java Program to Determine the class of an object

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Determine the class of an object
Java Program to Determine the class of an object

Write a Java Program to Determine the class of an object

PROGRAM: Java Program to Determine the class of an object

/*Java Program to Determine the class of an object*/

1: Check the class of an object using getClass()

class Test1 {
// first class
}

class Test2 {
// second class
}

class Main {
public static void main(String[] args) {
// create objects
Test1 obj1 = new Test1();
Test2 obj2 = new Test2();

// get the class of the object obj1
System.out.print(“The class of obj1 is: “);
System.out.println(obj1.getClass());

// get the class of the object obj2
System.out.print(“The class of obj2 is: “);
System.out.println(obj2.getClass());
}
}

2: Check the class of an object using instanceOf operator

class Test {
// class
}

class Main {
public static void main(String[] args) {
// create an object
Test obj = new Test();

// check if obj is an object of Test
if(obj instanceof Test) {
System.out.println(“obj is an object of the Test class”);
}
else {
System.out.println(“obj is not an object of the Test class”);
}
}
}

3: Check the class of an object using isInstance()

class Test {
// first class
}

 

class Main {
public static void main(String[] args) {
// create an object
Test obj = new Test();

// check if obj is an object of Test1
if(Test.class.isInstance(obj)){
System.out.println(“obj is an object of the Test class”);
}
else {
System.out.println(“obj is not an object of the Test class”);
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *