0

Let's say I have this simple code structure in which I need to create an abstract class and then to define some concrete objects of that type

public abstract class Foo {
    
    protected int var1;
    protected String var2;

    protected Foo(int var1, String var2) {
        this.var1 = var1;
        this.var2 = var2;
    }

    //abstract methods here
}

and

public class ConcreteFoo1 extends Foo{
   
   public ConcreteFoo(int var1, String var2) {
       super(var1, var2);
   }

   //methods override
}

Everytime I add new instance variables, or simply change those already present in the abstract class, I need to change also the concrete classes. Is there a way to avoid this kind of coupling the we do via super() dependency injection?

FrMan
  • 31
  • 8
  • 2
    Maybe composition is preferable over inheritance in you use case, check here for more info: https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance – AddeusExMachina Jun 17 '22 at 08:05
  • Maybe use ```protected abstract int provideVar1()``` in your abstract class Foo and initialize your instance variables using these in the Foo default constructor. You would need to implement these new methods every time you add a variable though. If you want to pass them to the constructor of implementing classes you have to update the implementing classes constructors anyway. – RedCrafter LP Jun 17 '22 at 08:46

0 Answers0