2011-12-11 66 views
1

我正在尝试学习Java,但是在将数组传递给构造函数时遇到了问题。 例如:如何将数组传递给构造函数?

应用类: byte[][] array = new byte[5][5]; targetClass target = new targetClass(array[5][5]);

目标类:

public class targetClass { 
    /* Attributes */ 
    private byte[][] array = new byte[5][5]; 

    /* Constructor */ 
    public targetClass (byte[][] array) { 
     this.array[5][5] = array[5][5]; 
    } 

} 

我会非常感激,如果你能告诉我怎样才能做到这一点。

+0

既然你学习Java的类名应该总是以大写字母开头。 – Bhushan

回答

5

首先,通常在Java类的名字开头大写,现在,你遇到的问题,它应该是:

public class TargetClass { /* Attributes */ 
    private byte[][] array; 

    /* Constructor */ 
    public TargetClass (byte[][] array) { 
     this.array = array; 
    } 
} 
+0

甜。谢谢! 我还有很多东西需要学习。 – bbalchev

+0

@BlagovestBalchev那是最棒的部分! :) – MByD

1

在你的应用程序类,下面应该工作:

byte[][] array = new byte[5][5]; 
TargetClass target = new TargetClass(array); // Not array[5][5] 

此外,为您的目标类,下面应该工作:

public class TargetClass { 
    /* Attributes */ 
    private byte[][] array; // No need to explicitly define array 

    /* Constructor */ 
    public TargetClass (byte[][] array) { 
     this.array = array; // Not array[5][5] 
    } 
} 

如前所述,类名通常是大写,所以这就是我对你的班名所做的。

2

你并不需要在申报的时候并初始化类中的数组。它可以设置为传递数组的引用。例如,

public class targetClass { 
    /* Attributes */ 
    private byte[][] array = null; 

    /* Constructor */ 
    public targetClass (byte[][] array) { 
     this.array = array; 
    } 

} 
0

我会假设你想给私人数组分配给数组传递的,而不是试图挑5,5元了传入的数组。

构造内部,语法应为:

this.array =阵列;

在应用时,它应该是

targetClass目标=新targetClass(数组);

1
public class targetClass { 
    /* Attributes */ 
    private byte[][] array = null; 

    /* Constructor */ 
    public targetClass (byte[][] array) { 
     this.array = array; 
    } 

} 

然后调用它像这样

byte[][] array = new byte[5][5]; 
targetClass target = new targetClass(array);