您的位置:首页 > 编程语言 > Java开发

Java基础系列--instanceof关键字

2018-03-02 11:06 417 查看
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/8492158.html

  instanceof关键字是在Java类中实现equals方法最常使用的关键字,表示其左边的对象是否是右边类型的实例,这里右边的类型可以扩展到继承、实现结构中,可以是其真实类型,或者真实类型的超类型、超接口类型等。

  instanceof左边必须是对象实例或者null类型,否则无法通过编译。

  instanceof右边必须是左边对象的可转换类型(可强转),否则无法通过编译。

  使用实例:

1     interface IFather1{}
2     interface ISon1 extends IFather1{}
3     class Father1 implements IFather1{}
4     class Son1 extends Father1 implements ISon1{}
5     public class InstanceofTest {
6         public static void main(String[] args){
7             Father1 father1 = new Father1();
8             Son1 son1 = new Son1();
9             System.out.println(son1 instanceof IFather1);//1-超接口
10             System.out.println(son1 instanceof Father1);//2-超类
11             System.out.println(son1 instanceof ISon1);//3-当前类
12             System.out.println(father1 instanceof IFather1);//4-超接口
13             System.out.println(father1 instanceof ISon1);//false
14         }
15     }


  执行结果为:

class Son1
class Father1


View Code

参考:Java关键字——instanceof

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: