zoukankan      html  css  js  c++  java
  • java 语法 java没学好,休想学好安卓!

    int...a 里面的...表示可变参数,也就是说这是一个长度不定的数组

    instanceof :

    instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例。
     
    举个例子:
     
    public interface IObject { 


    public class Foo implements IObject{ 


    public class Test extends Foo{ 


    public class MultiStateTest { 
            public static void main(String args[]){ 
                    test(); 
            } 

            public static void test(){ 
                    IObject f=new Test(); 
                    if(f instanceof java.lang.Object)System.out.println("true"); 
                    if(f instanceof Foo)System.out.println("true"); 
                    if(f instanceof Test)System.out.println("true"); 
                    if(f instanceof IObject)System.out.println("true"); 
            } 
    }
     
    输出结果:
    true 
    true 
    true 
    true
     
    另外,数组类型也可以使用instanceof来比较。比如
     
    String str[] = new String[2];
    则str instanceof String[]将返回true。
    2>

    JAVA的instanceOf

    当你拿到一个对象的引用时(例如参数),你可能需要判断这个引用真正指向的类。所以你需要从该类继承树的最底层开始,使用instanceof操作符判断,第一个结果为true的类即为引用真正指向的类。

    例如下面的例子:

    class Person{}
    class Student extends Person{}
    class Postgraduate extends Student{}
    class Animal{} 
    public class InstanceofTester {
    public static void main(String[] args) {
      instanceofTest(new Student());
    }
    public static void instanceofTest(Person p){
      // 判断p的真正类型
      if (p instanceof Postgraduate){
       System.out.println("p是类Postgraduate的实例");
      } else if(p instanceof Student){
       System.out.println("p是类Student的实例");
      } else if(p instanceof Person){
       System.out.println("p是类Person的实例");
      } else if(p instanceof Object) {
       System.out.println("p是类Object的实例");
      }
      /*if(p instanceof Animal){//此错编译错误,所以做注释
       System.out.println("p是类Animal的实例");
      }*/
    }
    }

    这个程序的输出结果是:p是类Student的实例

    Person类所在的继承树是:Object<--Person<--Student<--Postgraduate。

    这个例子中还加入一个Animal类,它不是在Person类的继承树中,所以不能作为instanceof的右操作数。

  • 相关阅读:
    使用postman模拟上传文件到springMVC的坑:the request was rejected because no multipart boundary was found
    win10 安装多个版本的jdk,如何切换
    String类的substring方法
    tomcat7.0配置CORS(跨域资源共享)
    win7下安装centos6.5后,开机无法进入选择双系统启动界面,只能启动centos的解决办法
    java位运算
    JDK源码--ArrayList浅析
    使用Jasperreporter生成入库出库单打印等报表操作
    centos6.5下安装zip格式的tomcat7和tomcat8,并同时运行
    Centos7配置文件共享服务器SAMBA三步曲(转)
  • 原文地址:https://www.cnblogs.com/yaya-Android/p/4564139.html
Copyright © 2011-2022 走看看