• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

override int... param with int[] breaks polymorphism

 
Ranch Hand
Posts: 209
13
VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

 
Bartender
Posts: 2419
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 209
13
VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2419
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic