Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an overriden method with a different return type?

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.

like image 287
Tru Avatar asked Nov 27 '22 17:11

Tru


2 Answers

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.

like image 157
Pablo Santa Cruz Avatar answered Dec 10 '22 22:12

Pablo Santa Cruz


"is this a seriously bad example of OO design" Yep. You can't do it.

like image 45
Matthew Adams Avatar answered Dec 10 '22 23:12

Matthew Adams