v11
v11

Reputation: 2234

How to change superclass member variable when extends

I have a supperclass:

public abstract class BasicDAO implements DAO{
    private static final Logger log = LoggerFactory.getLogger(BasicDAO.class);
    protected DBCollection Collection;
    @Override
    public DBCursor findByAll() {
        DBCursor cursor = Collection.find();
        log.debug("do something");
        return cursor;
    }
}

I extends this superclass:

public class TopicBasicDAO extends BasicDAO{
    private static final Logger log = LoggerFactory.getLogger(TopicBasicDAO.class);
}

I want to change the member variable log to subclass,but it can't override the member.How can I do?

Upvotes: 2

Views: 168

Answers (2)

Eran
Eran

Reputation: 393791

As commented, you can't override static members. I'll suggest an alternative. It seems like you need a different logger instance for each class in your hierarchy. This can be handled with a Map.

private static Map<Class,Logger> loggers = new HashMap<Class,Logger>();
....
public Logger getLogger ()
{
    Logger logger = null;
    if (BasicDAO.loggers.containsKey(this.getClass())) {
        logger = BasicDAO.loggers.get(this.getClass());
    } else {
        logger = LoggerFactory.getLogger(this.getClass());
        BasicDAO.loggers.put (this.getClass(), logger);
    }
    return logger;
}

Then, instead of accessing the logger directly, you write getLogger().debug("do something");

Upvotes: 1

Vijay Kansal
Vijay Kansal

Reputation: 839

Make the log variable protected and not final in superclass, then in your subclass you can modify it, i.e. in Superclass:

protected static Logger log = LoggerFactory.getLogger(BasicDAO.class);

and in Subclass:

public class TopicBasicDAO extends BasicDAO{
    log = LoggerFactory.getLogger(TopicBasicDAO.class);
}

Upvotes: 0

Related Questions