Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface (two methods, different return types depending on class) Java

Tags:

java

interface

Any class that extends an interface must implement the methods declared in the interface. Not sure if this is possible but what I want to do is the following :

interface test {
   ____ get();
}

class A extends test {
  int val;

  A(int x) {
    val = x;
  }

  int get() {
    return Val;
  } 


  class B extends test {
  String val;

  B(String x) {
    val = x;
  }

  String get() {
    return Val;
  } 

Is it possible to have a method signature that is able to return two different data types?

like image 357
halapgos1 Avatar asked May 08 '16 23:05

halapgos1


People also ask

Can we have two methods in a class with the same name but different return type?

We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types.

Can interface methods have return type in Java?

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Can interface methods have a return type?

Interface types act like class types. You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type.

Can an interface have 2 methods?

No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.


1 Answers

Not exactly like that but you can get close with a generic type parameter.

interface Test<T> {
    T get();
}

class A implements Test<Integer> {
    int val;

    A(int x) {
        val = x;
    }

    @Override
    public Integer get() {
        return val;
    }
}

class B implements Test<String> {
    String val;

    B(String x) {
        val = x;
    }

    @Override
    public String get() {
        return val;
    }
}

As you can see, you're bound to use Integer because generics don't work with primitives.

Also note, those 2 versions of the same interface are essentially 2 different interfaces now.

like image 182
zapl Avatar answered Sep 19 '22 16:09

zapl