Java之instanceof关键字
为了更好的说明,我下面通过代码举例说明。(Person有两个子类Man和Woman)
1、为什么java要使用instanceof关键字?
答:java在向下转型的过程中,运行过程中可能出现ClassCastException(类型转换异常),而instanceof就是来避免这个异常的。
2、使用情境:为了避免在向下转型时出现ClassCastException的异常我们在向下转型之前,先进行instanceof的判断。 一旦是返回true就进行向下转型,如果返回false就不进行向下转型。
3、如果a instanceof A返回true;那么a instanceof B也返回true。其中B类是A类的父类
package com.atguigu.java2;
public class Person {
String name;
int age;
public void eat() {
System.out.println("人吃饭!");
}
public void walk() {
System.out.println("人走路!");
}
}
package com.atguigu.java2;
public class Man extends Person{
boolean isSmoking;
@Override
public void eat() {
System.out.println("男人吃饭!");
}
@Override
public void walk() {
System.out.println("男人走路!");
}
public void earnMoney() {
System.out.println("男人挣钱养家!");
}
}
package com.atguigu.java2;
public class Woman extends Person{
boolean isBeauty;
@Override
public void eat() {
System.out.println("女人少吃,减肥!");
}
@Override
public void walk() {
System.out.println("女人窈窕的走路!");
}
public void goShopping() {
System.out.println("女人喜欢购物!");
}
}
package com.atguigu.java2;
public class PersonTest {
public static void main(String[] args) {
//对象的多态性:父类引用指向子类对象
Person p1 = new Man();
if(p1 instanceof Woman) {
Woman w1 = (Woman)p1;
w1.goShopping();
System.out.println("************woman***************");
}
if(p1 instanceof Man) {
Man w1 = (Man)p1;
w1.earnMoney();
System.out.println("************man***************");
}
if(p1 instanceof Person) {
System.out.println("************Person***************");
}
if(p1 instanceof Object) {
System.out.println("************Object***************");
}
}
}
调试结果
还没有评论,来说两句吧...