无法从主类看到我创建的数组对象的属性

时间:2012-05-25 21:03:39

标签: java arrays

类阻止

public class block {    
public enum size {SMALL,MEDIUM,LARGE,XLARGE}
    public String color;public size sz;

public block(String color, size sz) {
    super();
    this.color = color;
    this.sz = sz;
}
     public block() {
    this.color="White";
    this.sz=sz.SMALL;

}

public String toString() {
    String result="My color is " + color + " and size=" + sz;
    return result;}

类rowOfBlock

public class rowofBlocks extends block{

        private block[] blocks;
private int numofBlocks;

public rowofBlocks(int numofBlocks){
    //super();
    this.numofBlocks=numofBlocks;
    generateBlocks() ;
}

private void generateBlocks() {

    this.blocks=new block[numofBlocks];

}

public String toString() {
    for(int a=0;a<blocks.length;a++)
    {

    System.out.print( blocks[a]);
    }
    String a="d";
    return a;
}
}

类gameMain

public class gameMain {

    public static void main(String[] args) {



block b=new block();
b.setSz(block.size.LARGE);
b.setColor("WHITE");

    rowofBlocks myrows=new rowofBlocks(3);
    System.out.println(b);
    System.out.println(myrows);
    }}

我的意思是当我尝试创建块数组时,我只看到nullnullnulld而不是My color is White。

1 个答案:

答案 0 :(得分:0)

您获得了null个值,因为您没有在Block的数组中创建任何类RowOfBlocks的对象。

使用以下命令创建数组后

this.blocks = new block[numofBlocks];

generateBlocks()

的方法体中

你必须迭代它并插入实际的块:

for(int i=0 ; i < this.blocks.length ; i++) {
     this.blocks[i] = new Block();
}