-3

I am still confused about the general difference between upcasting and downcasting. How is it that sum of v23 is 132? Shouldn't it be 77 after upcasting?

I realize that overriding comes to take the place but then how can you get the access to the method of super-class if the function below seems to always refer to the method of the subclass?

Eran
  • 387,369
  • 54
  • 702
  • 768
Nathan Lee
  • 75
  • 1
  • 3
  • 10
  • 1
    the variable is declared to be `vec2` but the instance is still `vec3`, and that has overridden the method - the reason for overriding is exactly to use the overriding method instead of the original (e.g. `toString()`, ) . – user85421 Dec 14 '18 at 06:49
  • 3
    Please never post code as image. Post it as text. – janos Dec 14 '18 at 07:02
  • @Nathan Lee Please [https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-down-casting-with-respect-to-class] hit the link before & get your brain enlightened with the concept of Up-casting & Down-casting in Java. Probably, it is the best material at SO to get your doubt/confusion clarified!! – Abhinav Dec 14 '18 at 07:17

1 Answers1

0

I realize that overriding comes to take the place ....

Correct!

but then how can you get the access to the method of super-class if the function below seems to always refer to the method of the subclass?

You can't gain access to the method that has been overridden. That is fundamental to Java overriding.

Casting won't help you. Your v23 variable holds a reference to an object that is fundamentally and irrevocably a vec3 instance.

Thus, you are calling the version of sum that adds all 3 numbers: 33 + 44 + 55 -> 132.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216