Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do you prevent overloading?

 
Dave Tong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose I have the following:

class A {
int foo() {
return foo(true);
}
int foo(boolean flag) {
return 1;
}
}
class B extends A {
int foo() {
return foo(true);
}
int foo(boolean flag) {
return super.foo();
}
}

How do I ensure that A.foo() always calls A.foo(boolean) not B.foo(boolean)?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dave Tong:
...How do I ensure that A.foo() always calls A.foo(boolean) not B.foo(boolean)?

I think you're really asking, "How do I avoid polymorphism?" If you don't want this behavior, then you probably shouldn't have overridden methods.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make A.foo(boolean) private or final.
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its a very interesting and useful feature of java.In case you do not want then
follow Ilja's suggestion.
 
Dave Tong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest solution was to modify the code so that B.foo(boolean) could call super.foo(boolean) instead of super.foo()

Making A.foo(boolean) final would have broken the code
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dave Tong:
The simplest solution was to modify the code so that B.foo(boolean) could call super.foo(boolean)...

If that's the behavior you want, then why override foo(boolean) at all?
 
Dave Tong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:

If that's the behavior you want, then why override foo(boolean) at all?


Because it does more than just that. I simplified for the sake of clarity.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic