操纵对象,构造函数?

时间:2018-01-23 21:04:24

标签: java arrays object constructor

你好,英语不是我的主要语言 我不确定如何解释我的问题或者标题是否应该标题

所以......请跳到House课堂!
提前谢谢

主要课程

public class Main {

    public static void main(String[] args) {

        Furniture f1 = new Furniture("chair", 2);
        Furniture f2 = new Furniture("bed", 20);
        Furniture f3 = new Furniture("workbench", 7);
        Furniture f4 = new Furniture("drawer", 15);

        Furniture [] foo = {f1,f2,f3}; 

        // public House(Furniture[] fur)
        House h1 = new House(foo);

        //  public House(Furniture f, House p) 
        House h2 = new House(f4, h1);

    }

}

家具类

public class Furniture {

    String name;
    int weight;

    public Furniture(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }

    public static void display(Furniture f) {
    System.out.println("This furniture is a " + f.name + " and weights " + f.weight);
    }

}

众议院班级

// My House class contains one attribut which is an array of Furniture
public class House {

    Furniture[] fur;

    // Should build an empty house
    public House() {

    }

    // Should define the house with the array content
    public House(Furniture[] fur) {
        this.fur = fur;
    }

    // Should build an house containing the Furniture f and the furniture of the House p
    public House(Furniture f, House p) {

    // I'm so confused here, I'm not sure how to start 



    }

}

我已经考虑制作一个新的数组,其长度是房子中包含的数组并添加+1(对于家具f)然后做一个循环以获得房子p的所有家具并将它们添加到新的阵列与新家具f

我试着做p.length(p为房子),但它不起作用。我有点理解为什么但另一方面我没有,我怎么能访问房子的阵列?这是错误的做法,我找不到另一种方式

2 个答案:

答案 0 :(得分:1)

变量p不是数组(它是一个类(House类)),因此您不能直接使用p.length调用毛发的长度。而是使用p.fur.length;来获取fur数组的长度。因为这样你首先引用类:p.fur然后访问该类(fur)中的数组。

答案 1 :(得分:1)

你不能这样访问数组,因为你的House不是数组,你必须在其他地方说houseInstance.fur才能访问数组,其中houseInstance是House类的一个实例。

考虑如何用旧家具和另一件新家具制作新房子:

这是你如何使用你的方法来做到的:

    public House(Furniture f, House p) {

        // I'm so confused here, I'm not sure how to start 
        this.fur = new Furniture[p.fur.length+1];

        this.fur[0] = f; // Add new furniture

        // Make new instances of furniture from another house(They don't share reference but have same values)
        // Suggested way of doing it
        for(int i =0; i < p.fur.length;i++){
            this.fur[i+1] = new Furniture(p.fur[i].name, p.fur[i].weight);
        }
        /*
           This will share furniture reference between those 2 houses
            so changing one will change another
            This should be avoided
        for(int i =0; i < p.fur.length;i++){
            this.fur[i+1] = p.fur[i];
        }*/
    }