2
class BooleanWrap{
    boolean b = new Boolean("true").booleanValue(); 
}

当我尝试对下面的代码执行相同操作时,它不起作用:

class TestCode  {
    public static void main(String[] ar)  {
        TestCode tc = new TestCode().go();
    }

    void go() {
        //some code
    }
}

编译错误:

TestBox.java:6: 错误:不兼容的类型 TestBox t = new TestBox().go();

当我将方法的返回类型go()从更改void为类类型时,我不再收到错误消息。

class TestCode2 {
    public static void main(String[] ar) {
        TestCode2 tc2 = new TestCode2().go();
    }

    TestCode2 go() {
        //some code
    }
}

我刚刚在上面的代码中创建的对象(由 引用tc2)会发生什么?会被抛弃吗?

4

3 回答 3

3

This should work just fine:

class TestCode{
    public static void main(String[] ar){
        new TestCode().go();
    }

    void go() {
        System.out.println("Hello World");
    }
 }

Edit: Additional info

This way you can't save the created instance. It will get destroyed right away in the next garbage collection. So normally, to avoid this unneccessary creation and destruction a static method would be used if the instance itself is not needed.

class TestCode{
    public static void main(String[] ar){
        TestCode.go();
    }

    static void go() {
        System.out.println("Hello World");
    }
 }
于 2015-01-31T08:14:33.843 回答
3

TestCode tc = new TestCode().go()仅当go()方法返回 a时才有效TestCode,因为您将其分配给TestCode类型的变量。

在 的情况下TestCode2 tc2 = new TestCode2().go();,如果该go()方法返回对不同实例的引用TestCode2(即不是您调用的那个go()),则原始实例将不会在任何地方被引用,并且有资格进行垃圾回收。换句话说,tc2将引用由返回的实例go(),它不必与在 main 方法中创建的实例相同new TestCode2()

于 2015-01-31T08:11:42.853 回答
1

As Eran said, the method go() returns nothing, and you're trying to assing that nothing to a variable, your method needs to return something, a TestCode object in this case

于 2015-01-31T08:15:35.543 回答