0

Is it possible to override instance variable of base class in Java. I have this scenario.

class base {

    protected static final Logger LOGGER = LoggerFactory.getLogger(base.class);

}

class childA extends base
{
    // uses a lot of methods of base but should log childA instead of base
    // protected static final Logger LOGGER = LoggerFactory.getLogger(childA.class);
}

class childB extends base
{
     //uses a lot of methods of base but should log childB instead of base
    // protected static final Logger LOGGER = LoggerFactory.getLogger(childB.class);
}

Is the only solution to solve this, to leave the Logger in base unitinitalised and then pass it in the constructor of the base ??

Toni26
  • 489
  • 4
  • 11
  • No - fields are never overridden in Java; only methods are. – Jon Skeet Jul 19 '21 at 14:54
  • 2
    Your LOGGER is not an _instance_ variable. – k314159 Jul 19 '21 at 14:55
  • This [***smells***](https://martinfowler.com/bliki/CodeSmell.html) like a *premature optimization* to me. – Elliott Frisch Jul 19 '21 at 14:58
  • @ElliottFrisch it certainly smells of _something_ premature, but optimization? How is using a different logger name an optimization? – k314159 Jul 19 '21 at 15:02
  • @k314159 I agree, I think minimizing duplication is more like it, the OP wishes the class being passed to the logger was a different one based on the instance being used and they have to initialize it in every class. – Ruan Mendes Jul 19 '21 at 15:03
  • You could make this be an instance method called `getLogger()` which instantiated a weak map based on the instance type using `getClass()`. `getLogger()` is responsible for making sure just one logger is created per class. Or maybe one logger per instance is not a problem, and that is what @k314159 meant by optimization (minimizing the number of logger instances). See https://stackoverflow.com/a/12160613/227299 – Ruan Mendes Jul 19 '21 at 15:07
  • @JuanMendes That is what I meant by optimization. I would probably make `logger` private. And have one per type. And not worry about optimizing my `logger` further. Until I had to. Sometimes one can log too much. – Elliott Frisch Jul 19 '21 at 15:17
  • 1
    @JuanMendes there is no need to introduce your own map, because `LoggerFactory` already does this. – k314159 Jul 19 '21 at 15:20
  • @k314159 You're correct, so a base method `getLogger() {return LoggerFactory.getLogger(this.getClass())}` is good enough, as is suggested in the answer I linked. – Ruan Mendes Jul 19 '21 at 15:30
  • Does this answer your question? [Java Logging With Abstract Classes](https://stackoverflow.com/questions/12160540/java-logging-with-abstract-classes) – Ruan Mendes Jul 19 '21 at 15:30

0 Answers0