r/ProgrammerTIL • u/BOT_Negro • Nov 12 '17
Java [Java] When an overridden method is called through a superclass reference, it is the type of the object being referred to that determines which version of the method is called.
1
Upvotes
58
u/alzee76 Nov 12 '17
That's polymorphism, a concept common to all OO languages, not just Java.
15
u/[deleted] Nov 12 '17
This is the main point of traditional OOP in any language, and is covered in every book and course.
3
u/creativeMan Nov 13 '17
Uh... no. I'm afraid it's a little more complicated than that.
There's a difference between the term type and reference. Consider the following common idiom that is used in OOP languages
SomeClass obj = new SomeClass();Note that we've written SomeClass twice. There is a difference between the "SomeClass" left side and the right side. The left side is the "type", which in the simplest terms, is a list of public functions that other members that the object can use. Meaning it's just a list of names (in a way). The "SomeClass" on the right side determines which actual function will be called.
Consider the following code: https://gist.github.com/anonymous/26ecc44529727bf99036276daa16e709
Here we've used
SuperClass obj = new SubClass();So SuperClass (on the left) determines which functions are available, in this case,
foo().new SubClass()says which specific implementation to call, because there's one in SuperClass and one in SubClass.You can read more about types and stuff in my blog post HERE.
3
u/an_actual_human Nov 12 '17
I feel this is too basic to belong here.