| Author |
override int... param with int[] breaks polymorphism
|
Richard Hayward
Ranch Hand
Joined: Feb 15, 2012
Posts: 30
|
|
I've been trying a few experiments to explore K&B p74 q3.
Suppose I have a class Voop3 with method
void doStuff(int... doArgs){...}
Surprisingly, I can override that method in the descendant class Voop3Son with
void doStuff(int[] doArgs){...}
The reason I find this surprising is that it seems to break polymorphism.
An instance of Voop3Son called v3s is-a Voop3.
I would expect it to be able to do anything a Voop3 instance could do.
In particular, Voop3 has a method
void doStuff(int... doArgs){...}
I could call that method on an instance of Voop3, as I do at line 09.
However, if I try and make that same method call on v3s, as at line 05, it won't even compile.
In order to call that method, with those parameters, on a Voop3Son instance I have to refer to it via Voop3 reference variable as at line 13.
Isn't this breaking polymorphism?
Regards
Richard
|
 |
Himai Minh
Ranch Hand
Joined: Jul 29, 2012
Posts: 292
|
|
Var-args is equivalent to an array of args.
For example:
doStuff(int... a) is the same as doStuff(int[] a)
In your example, Voop3Son overrides the doStuff method in Voop3.
I hope it makes sense.
|
 |
Richard Hayward
Ranch Hand
Joined: Feb 15, 2012
Posts: 30
|
|
Hi Himai,
Himai Minh wrote:
doStuff(int... a) is the same as doStuff(int[] a)
The two versions of doStuff are not the same.
will compile
Will not compile.
Regards
Richard
|
 |
Himai Minh
Ranch Hand
Joined: Jul 29, 2012
Posts: 292
|
|
Yes. They are not the same.
But var-args is treated the same as an array of args.
For the doStuff(int...a) method , you can pass in new int [] {1,2,3} as the argument. I am sure it will compile.
|
 |
 |
|
|
subject: override int... param with int[] breaks polymorphism
|
|
|