Abstract class to implement two similar methods

C

Craig L. Taylor

I'm trying to extend from a class that has the following method in it:

abstract void setValue(int v);

But, instead of forcing a child class to have int v as an argument, I would
like the child to have the possibility to be able to declare a double as
well. Is there a way to have a parent say "If you inherit from me, you must
implement one of these two methods to work", like this:

// Child class must implement one of these
abstract void setValue(int v);
abstract void setValue(double v);
 
C

Chris Uppal

Craig said:
Is there a way to have a parent say "If you inherit from
me, you must implement one of these two methods to work", like this:

// Child class must implement one of these
abstract void setValue(int v);
abstract void setValue(double v);

No.

Probably the nearest you can get would be to provide sensible default
implementation of one of the methods in the parent class; something like:

// in abstract parent
abstract void setValue(double v);
void setValue(int i) { setValue((double)i); }

Of course, that would require all subclasses to provide the 'double' version
instead of the 'int' version, though they could always override both methods if
that made more sense.

-- chris
 
T

tzvika.barenholz

It may make sense to provide just one method in the abstract

abstract void setValue(Object o);

and the impl can decide what to put there.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top