我在接口中定义抽象方法非常费力。为什么?在与该接口有关的每个类中,必须实现一种称为“ getInstance”的方法。这些方法返回实际使用的实例。 那么如何在接口中为不同的类定义抽象方法呢?
public interface MyInterface {
public <<here is my question>> getInstance();
}
public class Class1() implements MyInterface {
public Class1 getInstance() {
return this;
}
}
public class Class2() implements MyInterface {
public Class2 getInstance() {
return this;
}
}
答案 0 :(得分:3)
请参阅my comment,您似乎不太想这样做。
您可以执行以下操作Khan Saab pointed out:将getInstance
的返回类型设为MyInterface
。但是,如果您需要访问不属于界面的Class1
或Class2
的功能,那将不起作用。
您可以使用泛型执行以下操作:
public interface MyInterface<T> {
public T getInstance();
}
public class Class1 implements MyInterface<Class1> {
public Class1 getInstance() {
return this;
}
}
public class Class2 implements MyInterface<Class2> {
public Class2 getInstance() {
return this;
}
}
但是,您不能(例如)拥有一个MyInterface
数组,并且在其中使用Class1
和Class2
的混合(没有instanceof
和强制转换)。
所有这些可能意味着您想做其他事情。
答案 1 :(得分:1)
我认为您可能会发现Generics的想法很有用:
例如:
接口
public interface TestWithGenerics<T> {
public T getInstance();
}
实施
public class TestImplementation implements TestWithGenerics<TestImplementation> {
@Override
public TestImplementation getInstance() {
return this;
}
}
但是,正如评论所说,这一切都让人觉得有些可笑。我发现单例是代码的味道。但是我不确定您的要求是什么,希望对您有所帮助。
答案 2 :(得分:1)
由于两个类都实现了接口MyInterface
,因此每个类的对象都将是MyInterface
类型。
public interface MyInterface{
public MyInterface getInstance();
// ....other methods
}
public class Class1 implements MyInterface{
@override
public MyInterface getInstance(){
return this;
}
//... other code
}
public class Class2 implements MyInterface{
@override
public MyInterface getInstance(){
return this;
}
//... other code
}
答案 3 :(得分:0)
太棒了:-) 最后,我实施了“ T.J.人群”。工作正常。非常感谢大家。您在创建“更好的”代码的道路上给了我非常有趣的提示……