[英]how to pass a private int to an objekt in another class in java
我尝试使用从Test2类到a的2个私有值,但是我收到一条错误消息,说a未初始化。 有人能帮我吗? (我是Java新手)
///////////////////////////////////////////////////// /////
public class Test{
Test2 a = new Test2(a.getTestArray(), a.getNum1());
///////////////////////////////////////////////////// ////////////////////////
public class Test2{
private int[] testArray = {1, 2, 3, 4};
private int num1 = 3;
public void setTestArray(int[] testArray){
this.testArray = testArray;
}
public void setNum1(int num1){
this.num1 = num1;
}
public int[] getTestArray(){
return this.testArray;
}
public int getNum1(){
return num1;
}
public Test2(int[] testArray, int num1){
this.testArray = testArray;
this.num1 = num1;
}
Test2 a = new Test(a.getTestArray(), a.getNum1());
您正在尝试对要初始化的事物( a
)调用方法,然后再为其分配值。
我怀疑您的意思是:
a anA = new a();
Test2 test2 = new Test(anA.getTestArray(), anA.getNum1());
您实际上并不想在Test
类中的某个字段上执行此操作,因为这样会得到StackOverflowError
,因为每次创建Test
时都会创建Test
,而Test
会创建Test
, Test
会创建Test
等。
您可能打算在一种方法中执行此操作,例如:
public class Test extends Test2 {
public static void main(String[] args) {
a anA = new a();
Test2 test2 = new Test(anA.getTestArray(), anA.getNum1());
}
}
请注意,您需要声明Test
是implements Test2
还是extends Test2
(分别取决于Test2
是接口还是类)。
请记住,您不能从未初始化的变量中调用方法,
在这条线
Test2 a = new Test2(a.getTestArray(), a.getNum1());
jvm尝试这样做:
Test2 a;
int temp1[] = a.getTestArray(); // this fails because 'a' is not initialized
int temp2 = a.getNum1());
a = new Test2(temp1, temp2 );
我建议您在测试中添加一个新的静态字段
private static int[] DEFAULT_TEST_ARRAY = {1, 2, 3, 4};
private static int[] DEFAULT_NUM = 3;
并在Test2中删除默认值
private int[] testArray;
private int num1;
创建静态属性时,可以使用类而不是变量来引用它们,而无需创建新对象。
Test2 a = new Test2(Test.DEFAULT_TEST_ARRAY, Test.DEFAULT_NUM );
ps。 您可以将DEFAULT_TEST_ARRAY,DEFAULT_NUM移至Test2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.