[英]How to implement an interface for different classes of different data types
Say you have an interface which has a sum
method, with two implementing classes A
and B
. 假设您有一个具有
sum
方法的接口,并且具有两个实现类A
和B
Class A
wants to sum two integers and class B
wants to sum two long. 类
A
要总结两个整数和类B
要总结两个长。 What will be the implementation of interface C
? 接口
C
的实现将是什么?
class A implements C{
sum(2,3);
}
class B implements C {
sum(2.0,3.0);
}
How C should be implemented? 应该如何实施C?
You can achieve this using a generic interface. 您可以使用通用接口来实现。 For Example
例如
interface C<T extends Number> {
T sum(T a, T b);
}
class A implements C<Long> {
@Override
public Long sum(Long a, Long b) {
return a+b;
}
}
class B implements C<Float> {
@Override
public Float sum(Float a, Float b) {
return a+b;
}
}
A generic interface can help you here. 通用界面可以为您提供帮助。 You can extend the
Number
class using Generics in Java 您可以使用Java中的泛型来扩展
Number
类
Interface 接口
public interface BaseInterface<T extends Number> {
T sum(T a, T b);
}
Integer Implementation 整数实现
public class ImplementationOne implements BaseInterface<Integer> {
@Override
public Integer sum(Integer a, Integer b) {
return a + b;
}
}
Double Implementation 双重执行
public class ImpelementationTwo implements BaseInterface<Double> {
@Override
public Double sum(Double a, Double b) {
return a + b;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.