ANONYMOUS wrote:
class BankAccount6 {
String ownerName;
int balance;
BankAccount6(String ownerName, int balance) {
this.ownerName = ownerName;
this.balance = balance;
}
BankAccount6(String ownerName) {
this.ownerName = ownerName;
this.balance = 0;
}
}
Hey! I'm wondering if the above example can be described as a form of polymorphism?
This is an example of method (in this case specifically constructor) overloading.
There is no universally accepted definition of polymorphism, but overloading is generally considered an example of "ad hoc polymorphism", where the behaviour of a method depends on the types of its arguments.
The general concept of polymorphism simply requires that the same "thing" (method, typically) takes on multiple different "forms" (in the case of methods, different implementations) in different contexts. Overloading is an example of this because for the same method name we get a different implementation based on the types of the arguments.
Java implements a number of different kinds of polymorphism, but so far the only one we have seen in class is "subtype polymorphism". Due to Java's inheritance rules, we can guarantee that, if we have a class Child extends Parent
, then Child
must have all the same public members that Parent
does. So any valid code that is written to work with a Parent
object is also valid if we substitute a Child
in its place. Due to dynamic dispatch, the same code may call different methods based on the real type of the object it has been given. Therefore the "form" of the methods called has changed, and so the code is polymorphic.