Try Khov
Try Khov

Reputation: 97

Does the Subclass constructor inherit variables from the Superclass constructor?

Given:

public class Counter {

   private int count;

   public Counter() {
      count = 5;
   }

   public void increment() {
      count++;
   }

   public void reset() {
      count = 0;
   }

   public int value() {
     return count;
   }
}

If I have a subclass with a defined function (not implicitly created), does the subclass constructor inherit the instance variable count from the superclass constructor? I ask this because I'm running into a bit of a confusion with regards to private count.

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
  }
}

Does the object modCounter have a count variable? If not, why is modCounter.increment() not giving me an error?

Upvotes: 1

Views: 1514

Answers (1)

Mureinik
Mureinik

Reputation: 311893

An inherited class has all the members of its superclass, although they may not be directly accessible to it (if they are private). In this case - yes, an instance of ModNCount has a count member. It cannot access it since it's private, but, as you've seen, it can affect its value using the increment and reset methods.

Upvotes: 2

Related Questions