【问题标题】:Generic Interface and Class example [closed]通用接口和类示例 [关闭]
【发布时间】:2018-04-20 08:08:09
【问题描述】:

我已经定义了一个简单的通用接口:

public interface I1 <A> {
    public void display1(A x);
}

还有一个简单的泛型类:

public class c11<A> implements I1<A> {

    @Override
    public void display1(A x) {
        System.out.println(x + " is of type " + x.getClass());
    }
}

当我尝试如下实例化时,出现错误:

int x = 5;
c11<Integer> s1 = new c11<Integer>(x);
s1.display1(x); 

非常感谢您的帮助。

【问题讨论】:

标签: java class generics interface


【解决方案1】:

您的 c11 类没有构造函数接受 int 参数(或 Integer 或泛型类型参数 A 或其他任何与 new c11&lt;Integer&gt;(x) 调用匹配的参数)。

添加构造函数:

c11 (A a) {
     ...
}

将解决问题。

【讨论】:

  • a 应该做什么呢?只有 OP 可以告诉...如果没有必要,我们还可以从构造函数调用中删除参数。但是,为什么类是泛型的(而不是方法)?
  • @Thilo 是的,只有 OP 才能说出构造函数应该如何处理 a
  • 不确定 OP 指的是什么。我只是在练习学习如何定义泛型类和接口。
  • @MelanieA OP 指的是你(问题的原始海报)
  • 感谢您的澄清和回复。你能告诉我应该用什么来代替 cosntructor 中的 ... 吗?
【解决方案2】:

如果你改变 new c11(x); 它肯定会起作用;到新的 c11();t 由于您没有定义任何构造函数,因此在实例化(创建)对象时不能调用参数化构造函数“c11(x)”。如果您想通过c11(x)创建对象,则更改代码如下

//interface
public interface I1 <A> {
public void display1();
}

//class
public class c11<A> implements I1<A> {
A x;
public c11(A obj){
  x=obj;  
}

@Override
public void display1() {
    System.out.println(x + " is of type " + x.getClass());
}
}

// and calling code
int x = 5;     
c11<Integer> s1 = new c11<Integer>(x);
s1.display1();

确保一个 java 文件只能有一个公共类或接口。

【讨论】:

  • 请修正您的代码缩进。
  • 好的。我会处理代码缩进。
  • 谢谢。你能告诉我为什么你从 display1 方法中删除了参数吗?
猜你喜欢
  • 2010-12-10
  • 2015-06-27
  • 2023-04-03
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 2015-04-06
  • 2016-09-27
  • 1970-01-01
相关资源
最近更新 更多