log4j中NOPLogger类构造函数使用未声明实例变量问题咨询
Why can NOPLogger assign
repository/level/parent without declaring them? Great question! Let's unpack this log4j detail step by step:
- First, remember that NOPLogger extends the
Loggerclass. Those three variables (repository,level,parent) aren't missing—they're defined directly in the parentLoggerclass. - In Java, subclasses inherit all non-private instance variables from their parent class. Log4j's base
Loggerclass declares these variables with at leastprotectedaccess (or package-private, if they share the same package), which lets subclasses like NOPLogger access and modify them directly using thethiskeyword.
To put it in context, the parent Logger class likely has something like this under the hood:
public class Logger { protected LoggerRepository repository; protected Level level; protected Logger parent; // Constructor, methods, and other core logic... }
- This design makes perfect sense for log4j's architecture: all logger subclasses share the same core state (like logging level, parent logger, and repository) defined in the base
Logger, so there's no need to re-declare these fields in every subclass. It keeps the code DRY (Don't Repeat Yourself) and maintains consistency across the logger hierarchy. - When NOPLogger sets
this.repository = repoand the others, it's simply initializing the inherited fields from its parent class, not creating new ones in the subclass.
内容的提问来源于stack exchange,提问作者Squeez
相关产品推荐
相关产品推荐

