I am trying to create a parent class in Java that passes static variables to each of it's child classes so that each of the child classes has its own copy.
Here is an example of the code:
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();
}
}
I don't want to have to recreate each of these classes and variables inside of each of the child classes. That would kind of defeat the purpose of having the parent.
Is this even possible or am I going to have to build it for each one? I think I might be able to do it with the <T> thing like the way they do the List<T> ... but I don't know enough about it or even what that is called.
Any help would be great.
<T>thing are generics