所以主要的动物类将生成 som cows,但实例化是在 cow 类中进行的。我的问题是:这种代码模式真的"OK"吗?或者应该将 cow 类重命名为"CowHandler",而是有一个名为 cow 的子类?
然后,CowHandler 将有一个字段List<Cow> cows;
,并且 Cow 类仅String name;
化自己感觉很奇怪,例如,带有奶牛列表的字段从未在 cow 类中使用过。这是截至目前的代码:
动物类
import java.util.List;
public class Animal
{
public static void main(String[] args)
{
Animal animal = new Animal();
animal.init();
}
private void init()
{
Cow cow = new Cow();
int count = cow.getCows().size();
System.out.println("Cows in list before: " + count);
List<Cow> manyCows = cow.makeSomeCows();
for (Cow c : manyCows)
{
System.out.println(c.getName());
System.out.println("Children?: " + c.getCows().size());
System.out.println("");
}
count = cow.getCows().size();
System.out.println("Cows in list after: " + count);
}
}
牛类
import java.util.ArrayList;
import java.util.List;
public class Cow
{
private String name;
private List<Cow> cows;
public Cow()
{
cows = new ArrayList<Cow>();
}
public List<Cow> makeSomeCows()
{
for (int i=0; i<10; i++)
{
Cow cow = new Cow();
cow.name = "Tiny cow " + ((char)(i + 65));
cows.add(cow);
}
return cows;
}
public String getName()
{
return this.name;
}
public List<Cow> getCows()
{
return this.cows;
}
}
输出:
Cows in list before: 0
Tiny cow A
Children?: 0
Tiny cow B
Children?: 0
Tiny cow C
Children?: 0
Tiny cow D
Children?: 0
Tiny cow E
Children?: 0
Tiny cow F
Children?: 0
Tiny cow G
Children?: 0
Tiny cow H
Children?: 0
Tiny cow I
Children?: 0
Tiny cow J
Children?: 0
Cows in list after: 10
只有在每个Cow
实例都有一个与其相关的Cow
列表(例如,该Cow
的子项(时,在Cow
类中具有private List<Cow> cows;
变量才有意义。
如果目的是拥有您创建的所有Cow
的容器,则 Cow
类中的实例变量是错误的,因为每个Cow
对象都有自己的List<Cow>
。
您可以在 Cow
类中使用 private static List<Cow> cows;
静态变量来保存所有Cow
实例,并使用相应的static
方法来访问它,但将列表放在 Cow
s 的单独容器上更有意义,例如 CowHandler
。但是请注意,Cow
成为 CowHandler
的子类是没有意义的。Cow
不是Cowhandler
.