我有一个接口,当我尝试实现其中一个方法时,我收到此错误: “GenericQueue中的名称冲突:入队(T#1)和IGenericQueue中的入队(T#2)具有相同的擦除,但是在T#1,T#2是类型变量的情况下都不会覆盖另一个: T#1扩展了GenericQueue类中声明的Comparable T#2扩展了接口IGenericQueue中声明的Comparable“ 这是代码:
public interface IGenericQueue <T extends Comparable> {
public void enqueue(T j);
..
}
public class GenericQueue<T extends Comparable> implements IGenericQueue {
....
public void enqueue(T j) // the error is in this line.
{
if(rear == maxSize -1)
rear = -1; // means you have reached the last element start again ?
queArray[++rear] = j;
nItems ++ ;
}
}
答案 0 :(得分:54)
您的GenericQueue
正在实施原始界面IGenericQueue
,因此其T
与T
中的IGenericQueue
不同。在<T>
子句中添加implements
:
public class GenericQueue<T extends Comparable> implements IGenericQueue<T> {
// ^^^
因此,您要使用相同的T
实现通用接口。
答案 1 :(得分:2)
我遇到了类似的问题,尽管我在OO编程的模板模式之后有一个更复杂的泛型类层次结构。哪里有一个接口,然后另一个接口扩展该接口,然后实现该接口的抽象类然后扩展抽象类的类,但是得到错误“接口和类。名称冲突:相同的擦除,但都没有覆盖其他”并发现只有当我在层次结构中的每个类中或者在每个类中引入该类之后,错误才会消失。 例如:
call
模板模式非常适合模块化设计,并且可以分解公共代码并有利于代码重用。要阅读有关模板模式的更多信息:https://en.wikipedia.org/wiki/Template_method_pattern
答案 2 :(得分:0)
功能接口->首先,让我们了解@FuntionalInterface
的概念,因为我们知道JDK-1.8
一种新概念被称为Lambda Expersion:
Lambda Expersion
您需要先了解有关LamdaExpersion的概念,然后才能轻松获得“什么是功能接口”角色。.
// Java program to demonstrate lambda expressions
// to implement a user defined functional interface.
// A sample functional interface (An interface with
// single abstract method
interface FuncInterface
{
// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun()
{
System.out.println("Hello");
}
}
class Test
{
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);
// This calls above lambda expression and prints 10.
fobj.abstractFun(5);
}
}
Lambda Expersion仅在您的定义接口只有 1个方法定义时起作用,因为Java编译器仅在interface中只有一个方法时才知道,因此您无需在您的类中定义该方法,因此:注释出现在图片中,当您要实现Lambda Expersion时,必须在界面中使用@FunctionInterface
。如果错误地在“接口”中编写了另一种方法,则编译器会告诉您这是“功能接口”。只需定义一种方法即可在您的应用程序中使用Lamda Experssion
@FunctionalInterface
interface sayable{
void say(String msg);
}
public class FunctionalInterfaceExample implements sayable{
public void say(String msg){
System.out.println(msg);
}
public static void main(String[] args) {
FunctionalInterfaceExample fie = new FunctionalInterfaceExample();
fie.say("Hello there");
}
}