我有一个名为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
对象的字段?
答案 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())