Java 子类构造函数是否从超类构造函数继承变量?

Java 子类构造函数是否从超类构造函数继承变量?,java,inheritance,constructor,subclass,private,Java,Inheritance,Constructor,Subclass,Private,鉴于: 如果我有一个定义了函数的子类(不是隐式创建的),子类构造函数是否从超类构造函数继承实例变量count?我问这个问题是因为我对私有计数有点困惑 public class Counter { private int count; public Counter() { count = 5; } public void increment() { count++; } public void reset() { co

鉴于:

如果我有一个定义了函数的子类(不是隐式创建的),子类构造函数是否从超类构造函数继承实例变量
count
?我问这个问题是因为我对
私有计数
有点困惑

public class Counter {

   private int count;

   public Counter() {
      count = 5;
   }

   public void increment() {
      count++;
   }

   public void reset() {
      count = 0;
   }

   public int value() {
     return count;
   }
}

对象
modCounter
是否有
count
变量?如果没有,为什么
modCounter.increment()
没有给我一个错误?

继承的类拥有其超类的所有成员,尽管它们可能无法直接访问(如果它们是
私有的
)。在本例中-是,
ModNCount
的实例有一个
count
成员。它无法访问它,因为它是私有的,但是,正如您所看到的,它可以使用
增量
重置
方法影响它的值。

是和否。
计数
存在,但由于它是私有的,您无法直接访问它。您确实可以访问公开声明的方法。这是相当标准的类继承。根据教程,
private
成员(字段和方法)并不是说是由其子类继承的。它们在“那里”,但子类无法访问它们,因此它们不在那里。
public class ModNCounter extends Counter {

  int modCount;

  public ModNCounter(int n) {
    modCount = n;
  }

  @Override
  public int value() {
    return super.value() % modCount;
  }

  public static void main(String[] args) {
    ModNCounter modCounter = new ModNCounter(3);
    System.out.println(modCounter.value()); //prints out 5 % 3 = 2
    modCounter.increment(); // count = 6
    System.out.println(modCounter.value()); //prints out 6 % 3 = 0
    modCounter.reset(); // count = 0
    modCounter.increment(); // count = 1
    System.out.println(modCounter.value()); //print 1 % 3 = 1
  }
}