Reputation: 49
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
Reputation: 588
The result is 2. Let's see.
Counter counter = new Counter();
gives us a counter
with addToNumber
and subtractFromNumber
methods.Counter superCounter = new SuperCounter();
gives us a superCounter
with addToNumber
method.int number = 3;
number = superCounter.subtractFromNumber(number);
Since superCounter does not override the old subtractFromNumber, it subtracts 1. Now number == 2
.number = superCounter.subtractFromNumber(number);
Same again, subtract 1, number == 1
.number = counter.addToNumber(number);
This method adds 1. Now number == 2
.The result is 2
, as we expected.
Upvotes: 5
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":
Upvotes: 1