How to check if an object is an instance of a class in Java

2 Answers

0 votes
public interface Animal {
 
    public void Showtalent(String talent);
    public void showDetails();
}
public class Dog implements Animal {
    public void Showtalent(String talent) {
        System.out.println("talent: " + talent);
    }
     
    public void showDetails() {
        System.out.println("I'm a dog");
    }
}
public class Example {
    public static void main(String[] args) {
        Animal dog = new Dog();
         
        System.out.println("dog instanceof Dog: " + (dog instanceof Dog));
        System.out.println("dog instanceof Example: " + (dog instanceof Example));
        System.out.println("dog instanceof Animal: " + (dog instanceof Animal));
    }
}
 
 
/*
run:
 
dog instanceof Dog: true
dog instanceof Example: false
dog instanceof Animal: true
 
*/

 



answered Jan 12, 2016 by avibootz
edited Jun 6, 2023 by avibootz
0 votes
class CTest1 {
}
 
class CTest2 {
}
 
public class MyClass {
    public static void main(String args[]) {
        CTest1 obj1 = new CTest1();
        if (obj1 instanceof CTest1) {
            System.out.println("yes");
        }
        else {
            System.out.println("no");
        }
 
        CTest2 obj2 = new CTest2();
        if (CTest2.class.isInstance(obj1)) {
            System.out.println("yes");
        }
        else {
            System.out.println("no");
        }
    }
}
 
 
 
 
/*
run:
 
yes
no
 
*/

 



answered Jun 6, 2023 by avibootz
...