Java instanceof用法詳解
Java 中的instanceof 運算符是用來在運行時指出對象是否是特定類的一個實例。instanceof通過返回一個布爾值來指出,這個對象是否是這個特定類或者是它的子類的一個實例。
用法:
1
|
result = object instanceof class |
參數:
Result:布爾類型。
Object:必選項。任意對象表達式。
Class:必選項。任意已定義的對象類。
說明:
如果 object 是 class 的一個實例,則 instanceof 運算符返回 true。如果 object 不是指定類的一個實例,或者 object 是 null,則返回 false。
例子如下:
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package com.instanceoftest; interface A{} class B implements A{ } class C extends B { } class instanceoftest { public static void main(String[] args){ A a= null ; B b= null ; boolean res; System.out.println( "instanceoftest test case 1: ------------------" ); res = a instanceof A; System.out.println( "a instanceof A: " + res); res = b instanceof B; System.out.println( "b instanceof B: " + res); System.out.println( "/ninstanceoftest test case 2: ------------------" ); a= new B(); b= new B(); res = a instanceof A; System.out.println( "a instanceof A: " + res); res = a instanceof B; System.out.println( "a instanceof B: " + res); res = b instanceof A; System.out.println( "b instanceof A: " + res); res = b instanceof B; System.out.println( "b instanceof B: " + res); System.out.println( "/ninstanceoftest test case 3: ------------------" ); B b2=(C) new C(); res = b2 instanceof A; System.out.println( "b2 instanceof A: " + res); res = b2 instanceof B; System.out.println( "b2 instanceof B: " + res); res = b2 instanceof C; System.out.println( "b2 instanceof C: " + res); } } /* result: instanceoftest test case 1: ------------------ a instanceof A: false b instanceof B: false instanceoftest test case 2: ------------------ a instanceof A: true a instanceof B: true b instanceof A: true b instanceof B: true instanceoftest test case 3: ------------------ b2 instanceof A: true b2 instanceof B: true b2 instanceof C: true */ |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/qq_35101189/article/details/58058421