[英]How to call a non-void method from a void method?
是否可以通過向其發送臨時對象來調用接收對象並從 void 方法返回 int 值的 int 方法?
當我嘗試這個時,我一無所獲; 輸出窗口出現一毫秒然后消失。 我使用了這個代碼:
class test {
int x (test ob) { return 10;}
public static void main (String args[]) { new test().x(new test()) }
}
是的。 如果它只需要任何對象,您可以傳遞new Object()
並接收 int 值作為結果。
總之一句話是的。 調用方法的返回類型對被調用方法的返回類型沒有影響。 例如:
public class SomeClass() {
public int increment(int i) {
return i + 1;
}
public void printFiveTheHardWay() {
System.out.println(increment(4));
}
}
是的,無論方法的返回類型如何,您都可以從 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();
}
}
因此,調用方法返回類型與被調用方法返回類型無關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.