ADVERTISEMENT
ADVERTISEMENT

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

Java example to check whether an object belongs to a particular class or not.
Submitted by Nidhi, on April 29, 2022

Problem Solution:

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.

Java Class and Object Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.