Consider the situation where I have an abstract class in Java;
public abstract class Foo
{
public abstract int myOperation();
}
Now, some of its subclasses may override myOperation like this;
class A extends Foo
{
public int myOperation()
{
// Do stuff
}
}
But if one subclass instead wants to return some other data type like;
class A extends Foo
{
public Object myOperation()
{
// Do stuff
}
}
I want the method name to be the same, to keep the design intact so that the clients don't necessarily select which method to call. Is there a workaround for this other than having separate methods with one being an empty implementation or using Object as the return type? Or is this a seriously bad example of OO design?
I've heard about Covariant return types in C++ and wondering whether Java has some other mechanism for this.
I'm also free to use an interface here.
You can't. Neither using inheritance, nor using an interface for this. It's going to be a compiler error so you won't be able to run your program at all.
You could return java.lang.Object
and return whatever object you want. In case you need to return a primitive, you could return its object wrapper.
"is this a seriously bad example of OO design" Yep. You can't do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With