如何使类具有在另一个类中创建的对象的字段

时间:2016-03-24 14:38:48

标签: java

我有一个名为NumFiles的类,它由矩阵数组组成:

public class NumFiles {

    private int[][] one = makeMatrix("one.txt");
    private int[][] two= makeMatrix("two.txt");
    private int[][] three= makeMatrix("three.txt");
    private int[][] four= makeMatrix("four.txt");
    private int[][] five= makeMatrix("five.txt");
    private int[][] six= makeMatrix("six.txt");
    private int[][] seven= makeMatrix("seven.txt");
    private int[][] eight= makeMatrix("eight.txt");
    private int[][] nine= makeMatrix("nine.txt");
    private int[][] zero= makeMatrix("zero.txt");

    public NumFiles() {
    }
    ...
}
然后我创建了另一个名为ImgClass的类,它需要有一个NumFiles对象的字段。在ImgClass中,需要访问NumFiles对象才能使用由它组成的矩阵。

我的问题是,如何调用NumFiles课程中的ImgClass对象?如何在另一个类中创建NumFiles对象的字段?

1 个答案:

答案 0 :(得分:2)

您可以在构造函数或setter中传递它,或者实例化字段:

public class ImgClass {
    private NumFiles numFiles; // choice 2,3,4
    // private NumFiles numFiles = new NumFiles(); // choice 1

    public ImgClass(NumFiles numFiles) { //choice 2
        this.numFiles = numFiles;
    }

    public ImgClass() { //choice 3
        this.NumFiles = new NumFiles();       
    }

    //public ImgClass() { //choice 1 or 4
    //}

    public void setNumFiles(NumFiles numFiles) { //choice 4
        this.numFiles = numFiles;
    }
}

选择1:

ImgClass imgClass = new ImgClass();

选择2:

ImgClass imgClass = new ImgClass(new NumFiles());

选择3:

ImgClass imgClass = new ImgClass();

选择4:

ImgClass imgClass = new ImgClass();
imgClass.setNumFiles(new NumFiles())