这里的编码初学者,所以请尽可能初学者友好!例如,我最近才了解到学校里的课程和对象。 另外,请原谅任何错误的命名/混淆:)
我已经有很多实例,我在写一个方法,但想要从中返回多个变量。我想 - "如果我创建了一个包含我正在使用的所有变量的类,然后从我的方法返回它的实例怎么办?
示例:
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;
}
}
现在请记住,这并不是我想做的事情,但实际上,我想使用一个类作为变量容器&#34;用在另一个类的方法中。 如果不是这样做的话,我想知道是什么(请尽量保持简单:))。
谢谢!
答案 0 :(得分:4)
public static Mathematics myMethod(int param1, String param2, float param3) {
Mathematics result = new Mathematics();
result.number1 = param1 * 2;
result.number2 = param2.length();
return result;
}
注意事项:
Mathematics
。Mathematics
课程相关,尽管他们可能会。{/ li>
new Mathematics()
实例化一个新对象,并为其指定一个任意名称。此外,我将其从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);