使用抽象类-Java的组成关系
Composition relation using abstract classes-Java
我有2个classes之间的关系:一个是抽象的class Region,另一个是class 肯肯。我在 class KenKen 中有一个区域类型的 ArrayList。如何在区域 class 中访问方法 addValue?
class如下:
肯肯:
public class KenKen {
private ArrayList<Region> regions;
public KenKen(String filename)throws FileNotFoundException{
//constructor
regions = new ArrayList<Region>();
//regions.addValue(0);//
}
public static void main(String[] args) throws FileNotFoundException{
KenKen kenken1 = new KenKen("input.1.txt");
}
}
地区:
public abstract class Region{
private int number = 0;
protected int target = 0;
protected ArrayList<Integer> values;
public Region(int number , int target){
this.number = number;
this.target = target;
//constructor
values = new ArrayList<Integer>();
}
public void addValue(int val){
}
public abstract boolean verify();
public String toString(){
}
}
您可以使用get()
方法来访问列表中的区域对象。
regions.get(0).addValue(0);
要访问 ArrayList
you should use get(int index)
的成员:
Returns the element at the specified position in this list.
所以:
regions.get(index).addValue(0);
regions 是区域的 ArrayList,你应该这样做
regions.get(index).addValue(x);
您需要 KenKen class 中的 public 方法来访问区域列表。
public List<Region> getRegions() {
return regions;
}
然后你可以调用 addValue()
getRegions().get(index).addValue(value);
我有2个classes之间的关系:一个是抽象的class Region,另一个是class 肯肯。我在 class KenKen 中有一个区域类型的 ArrayList。如何在区域 class 中访问方法 addValue?
class如下:
肯肯:
public class KenKen {
private ArrayList<Region> regions;
public KenKen(String filename)throws FileNotFoundException{
//constructor
regions = new ArrayList<Region>();
//regions.addValue(0);//
}
public static void main(String[] args) throws FileNotFoundException{
KenKen kenken1 = new KenKen("input.1.txt");
}
}
地区:
public abstract class Region{
private int number = 0;
protected int target = 0;
protected ArrayList<Integer> values;
public Region(int number , int target){
this.number = number;
this.target = target;
//constructor
values = new ArrayList<Integer>();
}
public void addValue(int val){
}
public abstract boolean verify();
public String toString(){
}
}
您可以使用get()
方法来访问列表中的区域对象。
regions.get(0).addValue(0);
要访问 ArrayList
you should use get(int index)
的成员:
Returns the element at the specified position in this list.
所以:
regions.get(index).addValue(0);
regions 是区域的 ArrayList,你应该这样做
regions.get(index).addValue(x);
您需要 KenKen class 中的 public 方法来访问区域列表。
public List<Region> getRegions() {
return regions;
}
然后你可以调用 addValue()
getRegions().get(index).addValue(value);