是否可以将接口类型转换为值?

Is it possible to convert interface type to a value?

我有一个接口:

public interface TestFace {
    public String outThis();
}

一个class方法的参数是接口类型,:

class MyClass {
    public void outMeth(TestFace inMeth){
        System.out.print(inMeth); //the method attempts to print the interface type
   }
}

如果我这样调用对象的方法:

MyClass a = new MyClass();
a.outMeth(new TestFace() {
            public String outThis() {
                String val = "something";
                return val;
            }
        });

打印的值是对实例的引用。有人可以解释为什么 happens/how 可以正确地做到这一点吗?

Object 执行 System.out.println 的结果将始终是调用对象的 toString() 方法的结果。如果您从 Object 继承它(通过不编写明确的 toString()),您将获得默认的 Object 实现,具体如下:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

匿名class的"name"一般反映了定义匿名class的class,通常加上</code>之类的到最后。</p> <p>如果你想要一个更有用的<code>toString(),覆盖它并自己写一个:

    new TestFace() {
        public String outie() {
            String val = "something";
            return val;
        }
        public String toString() {
            return outie();
        }
    }

如果你想打印val,只需覆盖toString()方法。

MyClass a = new MyClass();
a.outMeth(new TestFace() {
    public int outie() {
        int val = "something";
        return val;
    }

    @Override
    public String toString() {
        return outie();
    }
});