簡體   English   中英

我可以在Java中將對象用作方法的變量嗎?

[英]Can I use an object as a variable of a method in java?

這里是編碼的初學者,所以請盡可能對初學者友好! 例如,我最近才了解學校的課程和對象。 另外,請原諒任何錯誤的命名/混淆:)

我有很多實例,正在編寫一種方法,但想從中返回多個變量。 我想-“如果我創建一個包含所有正在使用的變量的類,然后從我的方法中返回它的實例怎么辦?

例:

public class Mathematics {
    int number1;
    int number2;
}

public class MyClass {
    public static void main (String [] args);


    public static <class?> MyMethod (<class Mathematics?>)
       //in here, the method works with numbers one and two, and then returns them, like so:
      return Mathematics;
    }
}

現在請記住,這並不是我真正想做的,但從本質上講,我想將一個類用作另一個類的方法中使用的“變量容器”。 如果這不是做到這一點的方法,我想知道是什么(請盡量保持簡單:))。

謝謝!

是的,您的方向正確! 這是一種常見的編碼模式,可以精確地解決此問題,即如何返回多個值。

public static Mathematics myMethod(int param1, String param2, float param3) {
    Mathematics result = new Mathematics();

    result.number1 = param1 * 2;
    result.number2 = param2.length();

    return result;
}

注意事項:

  1. 返回類型為Mathematics
  2. 參數可以是任何東西。 盡管可以,但它們不必與Mathematics課相關。
  3. 首先,使用new Mathematics()實例化一個新對象,並為其指定一個任意名稱。
  4. 然后,為每個字段分配一個您認為合適的值。
  5. 最后,返回該變量。

另外,我將其從MyMethod更改為myMethod以匹配標准Java命名約定。


然后,如果您想使用另一種方法使用該對象,則該方法應將Mathematics對象作為參數。

public static void otherMethod(Mathematics values) {
    System.out.println("number1 is " + values.number1);
    System.out.println("number2 is " + values.number2);
}

為什么在第一個方法返回它的同時將此方法作為參數? 區別在於方法是要接收一組值還是返回一個值。 如果要接收值,則需要一個Mathematics類型的參數。 如果它想將值返回給調用方,則其返回類型應為Mathematics

換句話說,值是輸入還是輸出?

順便說一下,這些並不是互斥的。 方法既可以接受也可以返回對象。 一個例子:

/**
 * Returns half of the input values. Does not modify the input object.
 * Instead, a new object is returned.
 */
public static Mathematics halfOf(Mathematics input) {
    Mathematics output = new Mathematics();

    output.number1 = input.number1 / 2;
    output.number2 = input.number2 / 2;

    return output;
}

然后可以這樣稱呼它:

Mathematics values  = myMethod(42, "foobar", 3.14);
Mathematics altered = halfOf(values);

System.out.println("Half of " + values.param1 + " is " + altered.param1);
System.out.println("Half of " + values.param2 + " is " + altered.param2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM