john
john

Reputation: 49

I dont understand this java inheritance example

I have been doing a mooc.fi course and im having a hard time understanding inheritance. This example in particular.

What does the program print?

public class Counter {

    public int addToNumber(int number) {
        return number + 1;
    }
    
    public int subtractFromNumber(int number) {
        return number - 1;
    }
}


public class SuperCounter extends Counter {

    @Override
    public int addToNumber(int number) {
        return number + 5;
    }
    
}



public static void main(String[] args) {
    Counter counter = new Counter();
    Counter superCounter = new SuperCounter();
    int number = 3;
    number = superCounter.subtractFromNumber(number);
    number = superCounter.subtractFromNumber(number);
    number = counter.addToNumber(number);
    System.out.println(number);
}

Apparently this isnt 6. Some help would be appreciated.

Upvotes: 1

Views: 672

Answers (2)

Danny
Danny

Reputation: 588

The result is 2. Let's see.

  1. Counter counter = new Counter(); gives us a counter with addToNumber and subtractFromNumber methods.
  2. Counter superCounter = new SuperCounter(); gives us a superCounter with addToNumber method.
  3. int number = 3;
  4. number = superCounter.subtractFromNumber(number); Since superCounter does not override the old subtractFromNumber, it subtracts 1. Now number == 2.
  5. number = superCounter.subtractFromNumber(number); Same again, subtract 1, number == 1.
  6. number = counter.addToNumber(number); This method adds 1. Now number == 2.

The result is 2, as we expected.

Upvotes: 5

V. Mokrecov
V. Mokrecov

Reputation: 1094

You have created 2 classes, and one inherits from the other (SuperCounter from Counter), which means that it inherits one method "subtractFromNumber" and overrides the other method "addToNumber".

Next, you create instances of these classes "counter" and "superCounter", while calling the method "subtractFromNumber" on the instance of the class "superCounter" 2 times and the method "addToNumber" on the other instance of the class "counter". But since you call the method "addToNumber" on the instance of the class "counter", respectively, the method of the class "Counter" is called.

According to the code, you get the answer "2":

  1. int number = 3; // 3
  2. number = superCounter.subtractFromNumber(number); // 3 - 1 = 2
  3. number = superCounter.subtractFromNumber(number); // 2 - 1 = 1
  4. number = counter.addToNumber(number); // 1 + 1 = 2
  5. System.out.println(number); // 2

Upvotes: 1

Related Questions