在Java中实例化构造函数中的不同类

时间:2013-06-18 16:20:56

标签: java arrays class object constructor

我是Java的新手刚刚开始研究简单的示例程序。

如何在B类的构造函数中创建A类实例。例如,我想在B类的构造函数中创建一个A类对象的数组。 psudo代码看起来像

class B {

public static A myarray;
B (int number){
  myarray = new A [number];
}

编辑:

public class TestClassA {

    public static int []  ArrayA = new int [6];
    TestClassA () {
        for (int i=0; i < 6; i++){
            ArrayA[i]=i;
            System.out.print("TestClassA ");
        }
    }
}

public class TestClassB {

    public TestClassA [] A;
    TestClassB (int num) {
        A = new TestClassA[num];
    }
}

public class Exec {

    public static void main (String[] args) {

        TestClassB B;
        B = new TestClassB(2);

    }
}

当我执行此操作时,我没有看到任何消息为“TestClassA”。我希望它创建2个TestClassA数组实例,因此我应该看到TestClassA 12次。不确定我在哪里做错了。

5 个答案:

答案 0 :(得分:3)

几个指针

  • 请勿使用static,除非您要与A的每个实例共享B个对象的数组。
  • 但是,您需要在声明引用时使用[],以表明它是Array
  • 同时设置您的会员字段private。然后通过publicprotected getter / setter方法控制对它们的访问。

您的代码应该是

public class B {

    private A[] arrayOfAobjects;

    B (int number) {
         arrayOfAobjects = new A[number];
    }

    public A[] getArrayOfAobjects() {
        return arrayOfAobjects;
    }
}

编辑 :(详细说明@ MikeStrobel下面的评论)
创建数组时,会根据Array的类型使用默认值对其进行初始化。例如,0的每个数组元素都设置为int []0.0的{​​{1}},double []对象的所有类型都设置为null阵列。

Object []

因此,您需要自己使用正确的值填充数组。在你的情况下,像

new int[100]; // creates an Array with 100 zeroes
new A[number]; // creates an Array of size "number"
               // but filled with nulls (instead of A objects)

编辑2

B (int number) {
     arrayOfAobjects = new A[number];
     for (int i=0; i < number; i++) {
         arrayOfAobjects[i] = new A(); // initialize the A[] array
     }
}

答案 1 :(得分:1)

如果你想要在B类构造函数中创建一个A类对象,你可以这样做:

class B { 
    public A object;
    B (int number){
      object= new A();
    }

class A{

    }

如果您想创建A类数组,请不要将变量设为静态。

class B { 
        public A[] myarray;
        int number = 5;
        B (int number){
          myArray = new A[number];
        }

class A{

        }

编辑:对象数组的语法(需要4个对象的数组)。

 A[] a = new A[4]; // Create the array of size 4.
 A a1 = new A(); //Create an object
 ............    //Similarly create other three objects
 a[0] = a1; //Add the object to the array
 ............   //Similarly add other three objects

答案 2 :(得分:0)

class B {

public A[] myarray;
B (int number){
  myarray = new A [number];
}

最好在私有或受保护模式下使用实例变量,并使用getter和setter方法来访问它。此代码仅创建一个未初始化的A对象数组。如果你想使用它们,你需要单独创建它们myarra[i]=new A();,其中i是任意数字0<=i<number

答案 3 :(得分:0)

这是你应该写的。

class B{
public A[] myArray;

B(int number){
  myArray = new A[number];
   }
  }

答案 4 :(得分:0)

public class B {

  private A[] arrayOfAs;

  public B (int number) {
     this.arrayOfAs = new A[number];
  }

  public getAs() {
     return this.arrayOfAs;
  }
}

不高于arrayofAs 静态,因为您不希望在B的所有实例之间共享您的数组。我还将它设为 private ,因为这被认为是实例变量的好习惯。

您可以使用上面的getAs()访问器方法将此数组返回到其他类。

相关问题