我发现interface能够直接赋给object:
假设i1是一个interface:IAmNewerObject o1 = i1; //可以通过编译但是,能不能从o1得出一个IAmNewer接口呢?怎么做?

解决方案 »

  1.   

    o1.getClass().getSuperclass()
    获取基类
      

  2.   

    有点糊涂,初步理解是任何interface都属于Object?然后下面的代码中的Test1.java的最后一句不通过? Why?//main\IAmNewer.java
    package main;public interface IAmNewer {
    String getName();
    }
    //main\IAmNewerImpl.java
    package main;public class IAmNewerImpl implements IAmNewer {
    private String name = "hello";

    public IAmNewerImpl () {
    super();
    } public String getName()
    {
    return name;
    }
    }
    //main\Test1.java
    package main;import main.*;public class Test1 {
    public static void main(String[] args)
    {
    IAmNewer i = new IAmNewerImpl();
    Object o = i;
    if (o.getClass().isInstance(i))
    System.out.println("yes, o is a IAmNewer."); String name = o.getClass().getSuperclass().getName();
    System.out.println("class name is: " + name);
    System.out.println("interface name is: " + o.getClass().getInterfaces[0].getName()); //OK

    IAmNewer i2 = (IAmNewer) o;
    System.out.println("the name is: " + i2.getName());
    System.out.println("class name is: " + i2.getClass().getName());
    System.out.println("interface name is: " + i2.getClass().getInterfaces[0].getName()); //failured???
    /*
    compiler error: symbol not found "getInterfaces"
    */
    }
    }
    为什么前面的getClass().getInterfaces[0].getName()可以通过编译而后面的不行?这说明interface又不完全是object?迷惑
      

  3.   

    汗,楼主getClass().getInterfaces[0].getName()能编译通过??
    都不可能编译通过
    正确的代码是:
    System.out.println("interface name is: " + o.getClass().getInterfaces()[0].getName()); System.out.println("interface name is: " + i2.getClass().getInterfaces()[0].getName());
      

  4.   

    thanks,昨晚通过几个小程序的练习,对object/interface终于有了进一步的认识了