【发布时间】:2018-01-26 19:08:37
【问题描述】:
我正在尝试在 Java 中创建一个父类,它将静态变量传递给它的每个子类,以便每个子类都有自己的副本。
下面是代码示例:
import java.util.*;
public class JavaFiddle {
public static void main(String[] args) {
Animal rex = new Dog("Rex", 3.2, 'M');
Animal luna = new Dog("Luna", 1.2, 'M');
Animal sadie = new Dog("Sadie", 0.1, 'F');
Animal daisy = new Dog("Daisy", 5.9, 'F');
Animal snowball = new Cat("Snowball", 3.8, 'M');
Animal tiger = new Cat("Tiger", 9.8, 'M');
System.out.println(Dog.getCount()); // output => 4
System.out.println(Cat.getCount()); // output => 2
}
}
class Animal {
protected static final List<Animal> list = new ArrayList<>(); // Each child class should get it's own static list
String name;
double age;
char gender;
Animal (String name, double age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
list.add(this); // This should add the child object to the the static list in the child class
}
public static int getCount() { // This should return the size of the static list for the child class
return list.size();
}
}
class Dog extends Animal {
protected static final List<Dog> list = new ArrayList<>(); // I don't want to have to add this for each child class. It should just get a copy from the parrent.
Dog (String name, double age, char gender) {
super(name, age, gender);
list.add(this); // I don't want to have to add this for each child class. It should just be added from the parrent.
// other stuff
}
public static int getCount() { // I don't want to have to add this for each child class. It should just get a copy from the parrent.
return list.size();
}
}
class Cat extends Animal {
protected static final List<Cat> list = new ArrayList<>(); // I don't want to have to add this for each child class. It should just get a copy from the parrent.
Cat (String name, double age, char gender) {
super(name, age, gender);
list.add(this); // I don't want to have to add this for each child class. It should just be added from the parrent.
// other stuff
}
public static int getCount() { // I don't want to have to add this for each child class. It should just get a copy from the parrent.
return list.size();
}
}
我不想在每个子类中重新创建这些类和变量。这有点违背了拥有父母的目的。
这甚至可能吗,还是我必须为每个人构建它?我想我可能可以用<T> 来做这件事,就像他们做List<T> ... 的方式一样,但我对此知之甚少,甚至不知道它叫什么。
任何帮助都会很棒。
【问题讨论】:
标签: java inheritance static