In Java, what does 'this' indicate in a superclass method called on a subclass that inherits that method?
Polymorphism & Overloading
Polymorphism
- Polymorphism is exhibited when a
reference.method()
is invoked
- This is by nature a dynamic behavior based on the actual
object
type referenced by the reference
- This is where the lookup tables(like vmt in c++) comes into play
- Depending on the object pointed by the reference, runtime will decide on the actual method to invoke
Overloading
- Method overloading in a compile time decision
- The signature of the method is fixed at compile time
- There is no runtime lookup needed for any polymorphism exhibited based on the method's parameter types
- The parameter is just a parameter for the method in context and it does not care about the polymorphism exhibited by the type
What is happening in the current example?
static class Lecture {
public void addAttendant(Person p) {
p.join(this);
}
}
- Assuming there is a child class of Lecture overriding
addAttendant
, then polymorphism can control which method will be called based on the object
type when someone invokes a method on a reference type of Lecture
or one of its subclass(es)
.
- But, for any call that will eventually land on the
Lecture.addAttendant
, the method signature that matches the p.join(this)
is join(Lecture)
(even though p
could be dynamically referenced). Here there is no polymorphism even though the object referenced by this
could be a polymorphic type.