Q:

Java program to check whether an object belongs to a particular class or not

belongs to collection: Java Class and Object Programs

0

Java program to check whether an object belongs to a particular class or not

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will check whether an object belongs to a particular class or not using the isInstance() method. The isInstance() returns a Boolean value.

Program/Source Code:

The source code to check whether an object belongs to the particular class or not is given below. The given program is compiled and executed successfully.

// Java program to check whether an object belongs 
// to a particular class or not

public class Main {
  public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    Class cls = Class.forName("Main");

    Main m = new Main();
    int val = 50;

    boolean res1 = cls.isInstance(m);
    boolean res2 = cls.isInstance(val);

    System.out.println("Is m instance of Main   : " + res1);
    System.out.println("Is val instance of Main : " + res2);
  }
}

Output:

Is m instance of Main   : true
Is val instance of Main : false

Explanation:

In the above program, we created a public class Main that contains a main() method. The main() method is the entry point for the program. Here, we checked whether an object belongs to the particular class or not using the isInstance() method. The isInstance() method returns true if the specified object belongs to the class otherwise it returns false. And, checked created objects belonged to the Main class or not and printed the appropriate result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to demonstrate the newInstance() meth... >>
<< Java program to check whether the specified Class ...