第二十六、Java面向对象之instanceof 关键字
2017-03-18 18:17
337 查看
instanceof是什么?
1:属于比较运算符:2:instanceof关键字:该关键字用来判断一个对象是否是指定类的对象。
3:使用格式:
对象 instanceof 类;
该表达式是一个比较运算符,返回的结果是boolea类型 true|false
注意:使用instanceof关键字做判断时,两个类之间必须有关系,判断的对象与指定的类别必须要存在继承或者实现的关系。
一般我们做强制类型转换之前都会使用该关键字先判断一把,然后在进行转换的。
class Animal{ String name; String color; public Animal(String name, String color){ this.name = name; this.color = color; } } //狗是属于动物中一种 class Dog extends Animal { public Dog(String name,String color){ super(name,color); //指定调用父类两个 参数的构造函数。 } public void bite(){ System.out.println(name+"咬人!!"); } } //老鼠 也是属于动物中一种 class Mouse extends Animal{ public Mouse(String name,String color){ super(name,color); } public void dig(){ System.out.println(name+"打洞.."); } } class MyClass{ public static void main(String[] args) { Dog d = new Dog("哈士奇","白色"); System.out.println("狗是狗类吗?"+ (d instanceof Dog)); System.out.println("狗是动物类吗?"+ (d instanceof Animal)); //System.out.println("狗是老鼠类吗?"+ (d instanceof Mouse)); // false true Animal a = new Animal("狗娃","黄色"); //狗娃是人 System.out.println("动物都是狗吗?"+ (a instanceof Dog)); } }
运行结果如下:
LoveQideMacBook-Pro:desktop loveqi$ java MyClass 狗是狗类吗?true 狗是动物类吗?true 动物都是狗吗?false
相关文章推荐
- JAVA面向对象-----instanceof 关键字
- JAVA面向对象-----instanceof 关键字
- Java面向对象-instanceof关键字
- Java面向对象高级--instanceof关键字
- java例程练习(对象转型及instanceof关键字)
- java -- 面向对象概述及static关键字
- 黑马程序员---java基础---面向对象中的构造方法及static关键字,变量的问题
- java自学笔记之抽象类,接口,对象的多态性,instanceof关键字
- 黑马程序员-------- java面向对象 封装、构造函数、this static关键字、单例设计
- [java学习笔记]java语言核心----面向对象之static关键字
- java 包关键字和面向对象总结
- 面向对象高级续2(instanceof关键字、抽象类和接口的应用、Object类、包装类)
- 黑马程序员--03.Java面向对象--02.【static关键字】【main方法】【静态成员】
- java面向对象_static关键字
- JAVA面向对象-----extends关键字
- [java学习笔记]java语言核心----面向对象之this关键字
- Java面向对象高级--final关键字
- Java面向对象基础--Static关键字的作用及使用
- 黑马程序员—Java面向对象(单例设计模式、面向对象的继承、final关键字)
- java学习-面向对象-概述-关键字-构造函数-单例