没有指定类型的Java接口

时间:2013-06-24 19:13:36

标签: java interface

我对界面设计有疑问。我将尝试用下面的一个简单例子来说明。

想象一下,我有一个界面:

public interface TestInterface {

    public List getData();

}

我有一个实施班:

public class TestInterfaceImpl implements TestInterface{

    public List<Customer> getData() {
        return null; //will return a list of customers
    } 
}

我这个糟糕的设计是在没有指定类型(List)的情况下在接口中返回List然后在实现类(List)中指定它?

谢谢 - 任何评论都表示赞赏。

3 个答案:

答案 0 :(得分:9)

在任何新代码中使用raw types都是一个坏主意。相反,parameterize the interface.

public interface TestInterface<T> {

    public List<T> getData();

}

public class TestInterfaceImpl implements TestInterface<Customer> {

    public List<Customer> getData() {
        return null; //will return a list of customers
    } 
}

如果您之前从未编写过通用类,或者只是不确定所有细节,那么您可能会发现the Java Tutorial's Generics Lesson非常有用。

答案 1 :(得分:3)

您可能想要使用参数化iface:

public interface TestInterface<T> {

    public List<T> getData();

}

public class TestInterfaceImpl implements TestInterface<Customer> {

    public List<Customer> getData() {
        return null; //will return a list of customers
    } 
}

答案 2 :(得分:3)

嗯,设计本身并不差,但泛型更好,类型安全的设计:

//parametrize your interface with a general type T
public interface TestInterface<T> {
    public List<T> getData();
}

//pass a real type to an interface
public class TestInterfaceImpl implements TestInterface<Customer> {
    public List<Customer> getData() {
        return null; 
    } 
}