Java instanceof判斷一個(gè)對(duì)象是否是一個(gè)類的實(shí)例
Java提供了instanceof關(guān)鍵字來判斷一個(gè)對(duì)象是否是一個(gè)類的實(shí)例(也可理解為是否可以轉(zhuǎn)換 為孩類的對(duì)象引用)instanceof操作示例如下:
[對(duì)象名]inslanceof [類名]
上面的表達(dá)式返回值為布爾值,一般出現(xiàn)在代碼的條件語句中
//父類
public class ParentClass {
}
//instanceof判斷一個(gè)對(duì)象是否是一個(gè)類的實(shí)例
public class ChildClass extends ParentClass{
public static void main(String[] args) {
ChildClass child1 = new ChildClass();
if(child1 instanceof ParentClass) {
System.out.println("child1為ParentClass的實(shí)例對(duì)象");
}
if(child1 instanceof ChildClass) {
System.out.println("child1為ChildClass的實(shí)例對(duì)象");
}
ChildClass child2 = new ChildClass();
if(child2 instanceof ParentClass) {
System.out.println("child2為ParentClass的實(shí)例對(duì)象");
}
if(child2 instanceof ChildClass) {
System.out.println("child2為ChildClass的實(shí)例對(duì)象");
}
}
}
點(diǎn)擊加載更多評(píng)論>>