-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFamilyVsExactType.java
More file actions
55 lines (47 loc) · 1.72 KB
/
FamilyVsExactType.java
File metadata and controls
55 lines (47 loc) · 1.72 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
49
50
51
52
53
54
55
// The difference between instanceof and class
package thinkinginjava.typeinfo;
import static thinkinginjava.util.Print.print;
//P333
/**
* Testing x of type class thinkinginjava.typeinfo.Base
* x instanceof Base true
* x instanceof Derived false
* Base.isInstance(x) true
* Derived.isInstance(x) false
* x.getClass() == Base.class true
* x.getClass() == Derived.class false
* x.getClass().equals(Base.class)) true
* x.getClass().equals(Derived.class)) false
* ==================
* Testing x of type class thinkinginjava.typeinfo.Derived
* x instanceof Base true
* x instanceof Derived true
* Base.isInstance(x) true
* Derived.isInstance(x) true
* x.getClass() == Base.class false
* x.getClass() == Derived.class true
* x.getClass().equals(Base.class)) false
* x.getClass().equals(Derived.class)) true
*/
class Base {
}
class Derived extends Base {
}
public class FamilyVsExactType {
static void test(Object x) {
print("Testing x of type " + x.getClass());
print("x instanceof Base " + (x instanceof Base));
print("x instanceof Derived " + (x instanceof Derived));
print("Base.isInstance(x) " + Base.class.isInstance(x));
print("Derived.isInstance(x) " + Derived.class.isInstance(x));
print("x.getClass() == Base.class " + (x.getClass() == Base.class));
print("x.getClass() == Derived.class " + (x.getClass() == Derived.class));
print("x.getClass().equals(Base.class)) " + (x.getClass().equals(Base.class)));
print("x.getClass().equals(Derived.class)) " + (x.getClass().equals(Derived.class)));
}
public static void main(String[] args) {
test(new Base());
System.out.println("==================");
test(new Derived());
}
}