简体   繁体   中英

how to pass a private int to an objekt in another class in java

i try to use the 2 private values from class Test2 to a but i get an error saying that a is not initialized. Can someone help me? (I am new to 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());

You're trying to call a method on the thing you're initializing ( a ), before you've assigned a value to it.

I suspect you mean something like:

a anA = new a();
Test2 test2 = new Test(anA.getTestArray(), anA.getNum1());

You don't actually want to do this on a field in class Test , because then you'll get a StackOverflowError , because you are creating a Test every time you create a Test , which creates a Test , which creates a Test etc.

You probably mean to do it inside a method, something like:

public class Test extends Test2 {
    public static void main(String[] args) {
      a anA = new a();
      Test2 test2 = new Test(anA.getTestArray(), anA.getNum1());
    }
}

Note that you need to declare that Test either implements Test2 or extends Test2 (depending upon whether Test2 is an interface or a class, respectively).

Remember that you can't invoke a method from an not initialized variable,

In this line

 Test2 a = new Test2(a.getTestArray(), a.getNum1());

the jvm trying this:

  Test2 a;
  int temp1[] = a.getTestArray(); // this fails because 'a' is not initialized
  int temp2 = a.getNum1());
  a = new Test2(temp1, temp2 );

i suggest you add a new static field in Test

private static int[] DEFAULT_TEST_ARRAY = {1, 2, 3, 4};
private static int[] DEFAULT_NUM = 3;

and in the Test2 remove default values

   private int[] testArray;
   private int num1;

As we create static attributes, we can use them without creating a new object, using the class as a reference instead of a variable.

Test2 a = new Test2(Test.DEFAULT_TEST_ARRAY,  Test.DEFAULT_NUM );

ps. you can move DEFAULT_TEST_ARRAY, DEFAULT_NUM to Test2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM