sanssan
sanssan

Reputation: 335

Java return type as Void and Object (More like Optional)

I would like to know if there is a way to implement interface method with void or Object?

For example...

Interface

public interface MyInterface {
     public XXXXXXX myMethod();
}

And

Implementation Class 1

public class MyClassOne implements MyInterface {
    public void myMethod() {
        System.out.println("MyClassOne");
    }
}

Implementation Class 2

public class MyClassTwo implements MyInterface {
     public String myMethod() {
         System.out.println("MyClassTwo");
         return "MyClassTwo";
     }
}

Upvotes: 0

Views: 2019

Answers (3)

davidxxx
davidxxx

Reputation: 131486

In a general way, I think what you try to do is not a good idea because with it, you cannot program as interface since according the implementation you expect for a result or no. Using a parameterized type with a Void shows the problem.

Indeed, you cannot have a typed return based on a type more or less precise. You handle an instance of Object type in the return.

For example :

MyInterface myInterface = new MyClassOne();
Object myMethod = myInterface.myMethod();

So, you must do instanceof or getClass to guess what to do... You don't do OOP anylonger. The interface loses its power.

If you need a method with a return and another without a return, create two methods. If you want to use a single method, you can keep the most broad (which one with the return type) and when you have no information to return,return null or a special value.

A method have to have a clear responsibility.

Upvotes: 0

vaski thakur
vaski thakur

Reputation: 92

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Upvotes: 0

user180100
user180100

Reputation:

You could use MyInterface<T> and the Void type for the void case:

public interface MyInterface<T> {
    T myMethod();
}

public class MyClassOne implements MyInterface<Void> {
    @Override
    public Void myMethod() {
        System.out.println("MyClassOne");
        return null;
    }
}

public class MyClassTwo implements MyInterface<String> {
     @Override
     public String myMethod() {
         System.out.println("MyClassTwo");
         return "MyClassTwo";
     }
}

Upvotes: 2

Related Questions