-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstanceOfExamples.java
More file actions
48 lines (33 loc) · 1.25 KB
/
InstanceOfExamples.java
File metadata and controls
48 lines (33 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.nishith.java.operators;
public class InstanceOfExamples {
public static void main(String[] args) {
// instanceof is used to check if an object is of a particular type.
SubClass subClass = new SubClass();
Object subClassObj = new SubClass();
SubClass2 subClass2 = new SubClass2();
SomeOtherClass someOtherClass = new SomeOtherClass();
System.out.println(subClass instanceof SubClass);// true
System.out.println(subClass instanceof SuperClass);// true
System.out.println(subClassObj instanceof SuperClass);// true
System.out.println(subClass2 instanceof SuperClassImplementingInteface);// true
// Since Super Class implements the interface, this is true
System.out.println(subClass2 instanceof Interface);// true
// Compile Error : If the type compared is unrelated
// System.out.println(subClass
// instanceof SomeOtherClass);//Compiler Error
// Object referred by subClassObj(SubClass)-NOT of type SomeOtherClass
System.out.println(subClassObj instanceof SomeOtherClass);// false
}
}
class SuperClass {
};
class SubClass extends SuperClass {
};
interface Interface {
};
class SuperClassImplementingInteface implements Interface {
};
class SubClass2 extends SuperClassImplementingInteface {
};
class SomeOtherClass {
};