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的右操作数。

posted @ 2015-06-09 17:36  guoliuya  阅读(319)  评论(0编辑  收藏  举报