Is it possible to make every class that extends another class have the same variable?
public abstract class Plant {
public static List<Plant> allPlants;
}
public class Tomato extends Plant {
public static List<Tomato> Tomatoes;
}
public class Potato extends Plant {
public static List<Potato> Potatoes;
}
// In another class...
new Potato();
new Tomato();
Plant.allPlants; // shows both the new potato and tomato
Potato.Potatoes; // shows only the new potato
Tomato.Potatoes; // Nothing
Tomato.allPlants; // Nothing
I am not so worried about having the allPlants
list, but I want it so that I can only access the list of specific plants from its class. Am I going to have to write out all of these lists or is there a better way of doing it?
CodePudding user response:
Based on the sample code you provide, your goal is to allow the constructor of each class to add the object created to the list of its class. For example, the Potato() constructor would add itself to Potato.Potatos and the constructor of the super class Plant would add itself to Plant.Plants.
And yes, you can use the same variable name in each of the classes. You only need the name of the class to use the correct variable.
Here's the code:
import java.util.*;
abstract class Plant {
public static List<Plant> plants = new LinkedList<>();
Plant(){ plants.add(this);}
}
class Tomato extends Plant {
public static List<Tomato> plants = new LinkedList<>();
Tomato(){ plants.add(this); }
}
class Potato extends Plant {
public static List<Potato> plants = new LinkedList<>();
Potato(){ plants.add(this); }
}
public class Main{
public static void main(String[] args) {
new Tomato(); new Tomato(); new Potato(); new Tomato();
System.out.println(Plant.plants); // 4 plants
System.out.println(Tomato.plants); // 3 tomato
System.out.println(Potato.plants); // 1 potato
}
}