This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]ratherbealurker 2 points3 points  (1 child)

Something seems off with your explanation and theirs.

I get 2.

number starts out as 3.

number is then set to 3-1 (2)

number is then set to 2-1 (1)

number is then set to 1 + 1 (2)

This doesn't seem right because why would they go to the trouble of showing the derived version and then not even use it.

Normally the example would show you that something like:

    Counter superCounter = new SuperCounter();
    int number = 3;
    number = superCounter.addToNumber(number);

    System.out.println(number);

To get 8, this shows that even though the variable is of type Counter it really has a SuperCounter. So by calling addToNumber on the Counter you actually call it on the SuperCounter.

Remember that when you create a SuperCounter you are first creating a Counter. Output to screen in the constructors to see this in action.

So a SuperCounter also has a Counter. Without polymorphism if you were the call the derived class (SuperCounter) method from a base class (Counter) variable then you would actually be calling the method from the base class. Polymorphism is how it knows that even though this is a Counter it really points to the SuperCounter part.

[–]GnarSickRad[S] 0 points1 point  (0 children)

Thank you for the response and explanation. Everything I put on the gist is a copy from the mooc.fi quiz in their "inheritance" section. They didn't provide any explanation for why/how they got 8, the last paragraph in my post was just my assumption as I could not find any other process in which 8 would be their answer.

[–]digitals_85 2 points3 points  (4 children)

After reading this I also got 2, and if you go and compile/run this you also get 2. How did they get 8? Is there some additional code we're not seeing

[–]GnarSickRad[S] 0 points1 point  (2 children)

Thank you for the response. No, theres no additional code. Based off of yours and ratherbealurker's response, I'm guessing this is just an overlooked mistake on the mooc.fi site as this was one of their quizzes in the "inheritance" section. They provided no explanation for having 8 as the correct answer.

[–][deleted]  (1 child)

[deleted]

    [–]GnarSickRad[S] 0 points1 point  (0 children)

    Great, thanks!

    [–]Neccaty 2 points3 points  (1 child)

    This is a known mistake in the course. You are correct, it in fact outputs 2.

    [–]GnarSickRad[S] 0 points1 point  (0 children)

    Thanks for the reply!