Java如何使用instanceof关键字?
要检查对象是否为特定类型的(class或interface输入),你可以使用instanceof运算符。该instanceof运算符仅用于对象引用变量。xinstanceofy可以理解为x是-一个y。
的instanceof返回true,如果被测试的引用变量是类型被进行比较。true如果所比较的对象的分配与右侧的类型兼容,它将仍然返回。
对于interface类型,如果任何对象的超类实现了接口,则称该对象为特定interface类型(意味着它将通过instanceof测试)。
package org.nhooo.example.fundamental;
public class InstanceofDemo {
public static void main(String[] args) {
Body body = new Body();
Hand hand = new Hand();
Nail nail = new Nail();
Shoes shoe = new Shoes();
if (body instanceof Man) {
System.out.println("body is a Man");
}
if (hand instanceof Man) {
System.out.println("hand is a Man too");
}
if (hand instanceof Body) {
System.out.println("hand is a Body");
}
//它应该返回false
if (hand instanceof Nail) {
System.out.println("hand is a Nail");
} else {
System.out.println("hand is not a Nail");
}
if (nail instanceof Man) {
System.out.println("nail is a Man too");
}
if (nail instanceof Hand) {
System.out.println("nail is a Hand");
}
if (nail instanceof Body) {
System.out.println("nail is a Body too");
}
//它应该返回false,因为Shoes不是工具Man
if (shoe instanceof Man) {
System.out.println("shoe is a Man");
} else {
System.out.println("shoe is not a Man");
}
//编译错误。不能测试不同的班级
//类层次结构。
//
//if(shoeinstanceofBody){
//}
}
}
interface Man {
}
class Body implements Man {
}
//间接实现人
class Hand extends Body {
}
//间接实现人
class Nail extends Hand {
}
class Shoes {
}上面的代码片段的结果:
body is a Man hand is a Man too hand is a Body hand is not a Nail nail is a Man too nail is a Hand nail is a Body too shoe is not a Man
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西