Java Interface Development

At first I had an interface as shown below.

public interface testMe {
      public Set<String> doSomething();
}
public class A implements testMe {
      public Set<String> doSomething() {
           return // Set<String>
      }
}

I had similar classes implementing testMe. Now I have to add another class that returnsSet<Some Object>

public class X implements testMe() {
     public Set<Some OBject> doSomething() {
     }
}

How can I add this method to the interface without breaking existing classes?

+3
source share
3 answers

You cannot for two reasons.

  • A class or interface cannot have two or more methods that have the same number and type of parameters with the same name, but with different types of return values; and

  • Due to type erasure, all instances Set<...>at runtime are simple Set, so they will have the same return type anyway.

You will need to name the second something else.

, :

public interface TestMe<T extends Serializable> {
  Set<T> doSomething();
}

public class A implements TestMe<String> {
  @Override
  public Set<String> doSomething() { ... }
}

public class X implements TestMe<ASerializableObject> {
  @Override
  public Set<ASerializableObject> doSomething() { ... }
}
+2

public interface testMe {
   public Set<?> doSomething();
}

public interface testMe {
   public Set<? extends CommonSuperclass> doSomething();
}
+5

I do not believe that you can, because erasing styles will destroy the effect that you have in mind.

You can parameterize the interface:

import java.util.Set;

public interface ISomething<T>
{
    Set<T> doSomething(T [] data);
}

And implementation:

import java.util.HashSet;
import java.util.Set;

public class Something<T> implements ISomething<T>
{
    public static void main(String[] args)
    {
        Something<String> something = new Something<String>();

        Set<String> set = something.doSomething(args);
        System.out.println(set);
    }

    public Set<T> doSomething(T [] data)
    {
        Set<T> foo = new HashSet<T>();

        for (T x : data)
        {
            foo.add(x);
        }

        return foo;
    }
}

I am not sure if this does what you mean.

+2
source

Source: https://habr.com/ru/post/1748075/


All Articles