There is a base abstract class Tank - it has some parameters and a constructor. A LightTank descendant class is created with the new armor parameter, all parameters are specified in the constructor. How to make a factory of tanks, so that depending on the incoming word LIGHT, MEDIUM, HEAVY, LightTank, MediumTank, HeavyTank objects are created that differ only in parameter values?

abstract public class Tank {...} public class LightTank extends Tank{ private int armor; public int getArmor() { return armor;} public Tank createTank(String model) { if (model.equals("LIGHT")) return new LightTank; else if.... 
  • one
    So what's the problem then? Override the armor value in the constructor of each child class and that's it. - Mikhail Chibel
  • If the Tank class returns in it there is no armor field? - Alexander
  • And where then do you want to use these fields, and why do you need them from the outside? Isn't it easier to make a virtual method and redefine it accordingly in each class? - awesoon
  • I would like to close them so that access was only through the getter and setter, if transferred to a tank and made them private, how to give them the value during initialization, while setArmore cannot be done, since the armore is set once and does not change anymore. I am a newbie and I don’t know everything, if they are set to final, then it is possible to assign an armore value to the LightTank class once in the heir? - Alexander

1 answer 1

I think you want something like

 abstract public class Tank { int getArmor(); } public class LightTank extends Tank { private int armor; public LightTank() { armor = 10; } public int getArmor() { return armor; } } public class HeavyTank extends Tank { private int armor; public HeavyTank() { armor = 100; } public int getArmor() { return armor; } } // фабрика public Tank createTank(String model) { if (model.equals("LIGHT")) { return new LightTank(); } else if (model.equals("HEAVY")) { return new HeavyTank(); } ... // получим значение armor для абстрактного танка tank.getArmor(); 
  • At home in the evening I will try and accomplish your goal, thanks - Alexander