如何从void方法调用非void方法?

时间:2019-01-20 07:17:07

标签: java function methods

是否可以调用一个int方法来接收一个对象,并通过向其发送一个临时对象来从void方法返回一个int值?

当我尝试这样做时,我什么也没得到;输出窗口将显示一毫秒并消失。我使用了这段代码:

class test {

    int x (test ob) { return 10;}

    public static void main (String args[]) { new test().x(new test()) }

}

3 个答案:

答案 0 :(得分:0)

是的。如果只需要任何对象,则可以传递new Object()并接收int值作为结果。

答案 1 :(得分:0)

总之,是的。调用方法的返回类型对被调用方法的返回类型没有影响。例如:

public class SomeClass() {
    public int increment(int i) {
        return i + 1;
    }

    public void printFiveTheHardWay() {
        System.out.println(increment(4));
    }
}

答案 2 :(得分:0)

是的,无论方法的返回类型如何,您都可以从Void方法中调用任何方法,例如:

您的评论示例如下:

class test {

    int x(test ob) {
        return 10;
    }

    public static void main(String args[]) {
        System.out.println(new test().x(new test()));
    }
}

更多通用代码供您更好地理解:

public class Foo {
    private Integer value;

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }
}

public class TestVoidMethodCall {

    public void voidMethod() {
        Foo f = new Foo();
        f.setValue(100);
        System.out.println(integerReturnMethod(f));
    }

    private Integer integerReturnMethod(Foo f) {
        return f.getValue();
    }
}

因此,调用方法的返回类型与被调用的方法的返回类型没有关系。

相关问题