![](/img/trans.png)
[英]How to properly pass an array as a parameter in a class copy constructor (Java OOP)
[英](Java) Pass a parameter from a constructor to all the methods of a class
说我在类1中有两个方法。是否可以将参数传递给类1构造函数,然后再将参数传递给两个方法? 类似于下面的示例代码:
class stuff{
int c;
stuff(x){
c = x;
}
public static int sum(int a, int b){
stuff self = new stuff();
return c*(a + b);
}
public static int mult(int a, int b){
return c*(a*b);
}
}
class test{
public static void main(String args[]){
stuff foo = new stuff(5);
System.out.println(stuff.sum(1, 2));
System.out.println(stuff.mult(1, 2));
}
}
因此,从类测试中,我想在传递方法参数的同时访问类材料中的两个方法,但是我还想传递全局类参数(在这种情况下为5)。 我怎样才能做到这一点?
只需从您的方法中删除“ static”关键字,就不要在sum方法中创建“ stuff”的新实例。 而是像现在一样在test#main方法中创建东西的实例,它可以按您想要的方式工作。
前两个重要事项:
在您撰写时:
class Stuff{
int c;
Stuff(x){
c = x;
}
...
}
在这里,您将x
分配给c
字段。
但是sum()
和mult()
是静态方法。
他们不能使用c
字段。
使这些方法成为实例方法,您可以在这些方法中使用c
。
public static void main(String args[]){
Stuff foo = new Stuff(5);
System.out.println(foo.sum(1, 2));
System.out.println(foo.mult(1, 2));
}
并在这些实例方法中使用当前实例将当前值与传递的参数值相加或相乘:
public int sum(int a, int b){
return c*(a + b);
}
public int mult(int a, int b){
return c*(a*b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.