質問

I have a Java interface A defining a method which takes another interface B as a parameter. I want to know if it is possible to overload that method in an implementing class to give as a parameter an object which implements the interface B. Here's a sample code of what I mean:

public interface SampleInterfaceA{
    public void sampleMethod(SampleInterfaceB b);
}

public class ClassB implements SampleInterfaceB{}
public class ClassC implements SampleInterfaceB{}

public class SampleClassA implements SampleInterfaceA{
    @Override
    public void sampleMethod(ClassB b){}
}

public class SampleClassB implements SampleInterfaceA{
    @Override
    public void sampleMethod(ClassC c){}
}

Thanks in advance for your help.

役に立ちましたか?

解決

If you try it, you'll see that SampleClassA and SampleClassB are seen by the compiler as missing something needed to implement SampleInterfaceA.

You need to implement the actual method defined in the interface.

A way to get approximately what you seem to want is to use generics:

public interface SampleInterfaceA <T extends SampleInterfaceB>{
    public void sampleMethod(T b);
}

public class SampleClassA implements SampleInterfaceA<ClassB>{
    public void sampleMethod(ClassB b){}
}

public class SampleClassB implements SampleInterfaceA<ClassC>{
    public void sampleMethod(ClassC c){}
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top