“无法实例化类型...”
当我尝试运行此代码时:
import java.io.*;
import java.util.*;
public class TwoColor
{
public static void main(String[] args)
{
Queue<Edge> theQueue = new Queue<Edge>();
}
public class Edge
{
//u and v are the vertices that make up this edge.
private int u;
private int v;
//Constructor method
public Edge(int newu, int newv)
{
u = newu;
v = newv;
}
}
}
我收到此错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot instantiate the type Queue at TwoColor.main(TwoColor.java:8)
我不明白为什么我无法实例化该类...这对我来说似乎是正确的...
When I try to run this code:
import java.io.*;
import java.util.*;
public class TwoColor
{
public static void main(String[] args)
{
Queue<Edge> theQueue = new Queue<Edge>();
}
public class Edge
{
//u and v are the vertices that make up this edge.
private int u;
private int v;
//Constructor method
public Edge(int newu, int newv)
{
u = newu;
v = newv;
}
}
}
I get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot instantiate the type Queue at TwoColor.main(TwoColor.java:8)
I don't understand why I can't instantiate the class... It seems right to me...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
java.util.Queue
是一个接口,因此您无法直接实例化它。您可以实例化一个具体的子类,例如LinkedList
:java.util.Queue
is an interface so you cannot instantiate it directly. You can instantiate a concrete subclass, such asLinkedList
:Queue 是一个接口,因此您不能直接启动它。由其实现类之一启动它。
从文档中所有已知的实现类:
您可以根据您的要求使用上述任何一个来启动 Queue 对象。
Queue is an Interface so you can not initiate it directly. Initiate it by one of its implementing classes.
From the docs all known implementing classes:
You can use any of above based on your requirement to initiate a Queue object.
队列是一个接口而不是一个类。
Queue is an Interface not a class.
您正在尝试实例化一个接口,您需要给出您想要使用的具体类,即
QueuetheQueue = new LinkedBlockingQueue();
。You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e.
Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();
.你可以使用
或者
原因:Queue是一个接口。所以你只能实例化它的具体子类。
You can use
or
Reason: Queue is an interface. So you can instantiate only its concrete subclass.
我遇到了同样的问题,无法实例化我绝对确定不是抽象的类的类型。结果我是从 Java.util 实现一个抽象类,而不是实现我自己的类。
因此,如果前面的答案对您没有帮助,请检查您是否
导入
您真正想要导入的类,而不是 IDE 可能提示您的同名的其他内容。例如,如果您尝试从您自己编写的包 myCollections 中实例化类 Queue :
I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from
Java.util
instead of implementing my own class.So if the previous answers did not help you, please check that you
import
the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :