2

I decide to override autowired field in sub class. How can I do this override? Something like this

class Superclass {
    @Autowired
    Test test;

    public Test getTest() {
        return test;
    }
}

class Subclass extends Superclass {
    @Autowired
    Test2 test2;

    public Subclass() {
        super().test=test2;
    }
}
dur
  • 15,689
  • 25
  • 79
  • 125
Ahmad R. Nazemi
  • 775
  • 10
  • 26
  • 1
    Possible duplicate of [Is there a way to override class variables in Java?](http://stackoverflow.com/questions/685300/is-there-a-way-to-override-class-variables-in-java) – Gary May 21 '16 at 20:46
  • 1
    Definitely not a duplicate of that question. – Andrew Spencer May 16 '18 at 10:02

2 Answers2

2

If understand correctly you want to have the value test2 auto filled and the method test() to use this new value.

There is no way in java to override a class variable, at least using a protected field will allow you to modify it's value in the subclass. But in this case i think it's better to override the getTest() method to return test2 instead.

dok
  • 90
  • 5
2

thanks from @dok solution i override field by this way:

class Superclass {
    private Test test;

    @Autowired
    public Test getTest(Test test) {
        return this.test = test;
    }
}

class Subclass extends Superclass {
    @Override
    @Autowired
    public Test getTest(Test2 test2) {
        return super.getTest(test2);
    }

}
Ahmad R. Nazemi
  • 775
  • 10
  • 26