Created
November 11, 2015 04:08
-
-
Save jlwatkins/34527890eef193939631 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InstanceofDemo { | |
public static void main(String[] args) { | |
Parent obj1 = new Parent(); | |
Parent obj2 = new Child(); | |
System.out.println("obj1 instanceof Parent: " | |
+ (obj1 instanceof Parent)); | |
System.out.println("obj1 instanceof Child: " | |
+ (obj1 instanceof Child)); | |
System.out.println("obj1 instanceof MyInterface: " | |
+ (obj1 instanceof MyInterface)); | |
System.out.println("obj2 instanceof Parent: " | |
+ (obj2 instanceof Parent)); | |
System.out.println("obj2 instanceof Child: " | |
+ (obj2 instanceof Child)); | |
System.out.println("obj2 instanceof MyInterface: " | |
+ (obj2 instanceof MyInterface)); | |
} | |
} | |
class Parent {} | |
class Child extends Parent implements MyInterface {} | |
interface MyInterface {} | |
Output: | |
obj1 instanceof Parent: true | |
obj1 instanceof Child: false | |
obj1 instanceof MyInterface: false | |
obj2 instanceof Parent: true | |
obj2 instanceof Child: true | |
obj2 instanceof MyInterface: true | |
When using the instanceof operator, keep in mind that null is not an instance of anything. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment