类中缺少实例变量但存在于构造函数中

时间:2018-04-06 10:24:19

标签: java

下面提到的log4j中有一个类

public final class NOPLogger
  extends Logger
{
  public NOPLogger(NOPLoggerRepository repo, String name)
  {
    super(name);
    this.repository = repo;
    this.level = Level.OFF;
    this.parent = this;
  }

正如你可以看到NOPLogger的构造函数中有四个参数。

第一个参数super(name)我可以理解从Logger(Parent类)派生,但是其他三个实例变量呢。根据我的知识,他们应该在班级宣布,但不会出现,你可以看到。当我追踪这些变量时,我发现它们在下面的类

public class Category
  implements AppenderAttachable
{
  protected String name;
  protected volatile Level level;
  protected volatile Category parent;
  private static final String FQCN = Category.class.getName();
  protected ResourceBundle resourceBundle;
  protected LoggerRepository repository;
  AppenderAttachableImpl aai;
  protected boolean additive = true;

我是否知道如何在构造函数(NOPLogger)中考虑这三个变量,甚至不首先在类级别声明它们(NOPLogger)?

我只是好奇地知道,并且只是解释了我已经知道的事情(我错了吗?)并且想知道在哪里理解这个概念?

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

NOPLoggerLogger的孩子,Category本身就是protected的孩子。

  

NOPLogger - >记录器 - >分类

NOPLogger字段由直接子类继承,但也由它们的子类继承为JLS states s:

  

<强> 6.6.2.1。访问受保护的会员

     

设C是声明受保护成员的类。访问是   只允许在C的子类S的主体内使用。

CategoryNOPLogger的(间接)子类,可以预期protected实例可以访问Category中定义的const emoji = bot.emojis.get(emojiID); await message.channel.send({files: [ { attachment: emoji.url, name: emoji.name + '.png' } ]}); 个实例字段。

答案 1 :(得分:1)

您所追求的链接是声明NOPLogger的继承层次结构。 Category类为这三个字段提供了受保护的访问权限,因此可以从继承层次结构中的子类访问它们。 Catetory -> Logger -> NOPLogger

  protected String   name; 
  volatile protected Level level;
  volatile protected Category parent;
相关问题