2015-11-19 132 views
0

我是Java新手。请帮助我使用此代码。泛型类型的调用方法

我正在创建一个具有泛型参数的实用程序类。在实用类的API中,我调用了一些泛型类型的API。

我假设这个类的用户将只传递具有此API(getInt在我的情况下)实现的通用。

public class Utility <DataType> { 

    private DataType d; 

    public Utility (DataType d_) 
    { 
     d = d_; 
    } 

    public int getValue() 
    { 
     return d.getInt(); 
    } 
} 

请指出我在做什么错在这里。

d.getInt()中的编译错误。无法解析getInt方法。

我加入了抽象接口:

abstract interface DataType { 
    public int getInt(); 
} 

但仍然是一个示数出来。

+0

你在'DataType'中有'getInt()'方法吗? – dguay

+0

当前没有DataType类。由于它是通用的,用户将在其代码中定义它。这个工具类在库中。 –

+0

如果还没有方法,并且你希望用户在他的代码中实现它,这会创建'DataType'作为接口,那么用户应该实现它,否则编译器会一直抱怨 – Salah

回答

1

你不能简单地向你的编译器承诺一个方法将存在于所有派生类中。你必须让它存在。你必须定义它。使用继承或接口来实现。

选项1继承

定义与一个抽象方法getInt()一个抽象基类。所有非抽象儿童必须执行getInt()

public abstract class DataType() { 
    public abstract int getInt(); 
} 

这个类的儿童是这样的:

public class MyDataType() extends DataType { 
    public int getInt() { 
     return 3; 
    } 
} 

选项2接口

定义的接口与方法getInt()。所有实现该接口的类都必须定义一个方法getInt()。顺便说一句,接口名称通常是形容词。

public interface DataTypeable { 
    public int getInt(); 
} 

此接口的实现应该是这样的:

public class MyDataType() implements DataTypeable { 
    public int getInt() { 
     return 5; 
    } 
} 

现在你Utility类可以使用基类或接口这样的(与DataTypeable取代DataType,如果你去的接口路径:

public class Utility { 

    private DataType d; 

    public Utility(DataType d) { 
     this.d = d; 
    } 

    public int getValue() { 
     return d.getInt(); 
    } 
} 

选项3.泛型加上其他选项之一

为了实际回答问题,下面介绍如何强制它使用泛型。

public class Utility <T extends DataType> { // or <T implements DataTypeable> 

    private T d; 

    public Utility(T d) { 
     this.d = d; 
    } 

    public int getValue() { 
     return d.getInt(); 
    } 
} 

然而,在这种情况下DataType必须是上面提到的其他选项之一。这里使用泛型是没有意义的。

2

这可能是你在找什么:

相反的Utility<DataType>,你需要一个类型的占位符。将其替换为Utility<T>并将所有DataType替换为T

public class Utility <T extends DataType> { 

    private T d; 

    public Utility (T d_) 
    { 
     d = d_; 
    } 

    public T getValue() 
    { 
     return d; 
    } 
} 
0

正如我的理解,你想使用DataType作为一个通用的对象。所以我不认为你必须创建接口DataType。只需要获得如下代码所示的数据类型值:

public class Utility<DataType> { 

    private DataType d; 

    public Utility (DataType d_) 
    { 
     d = d_; 
    } 

    public DataType getValue() 
    { 
     return d; 
    } 
} 

希望得到这个帮助!