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…
asked Apr 28, 2011 at 4:40
1
java.util.Queue
is an interface so you cannot instantiate it directly. You can instantiate a concrete subclass, such as LinkedList
:
Queue<T> q = new LinkedList<T>;
answered Apr 28, 2011 at 4:44
Cameron SkinnerCameron Skinner
51.3k2 gold badges65 silver badges85 bronze badges
0
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:
- AbstractQueue
- ArrayBlockingQueue
- ArrayDeque
- ConcurrentLinkedQueue
- DelayQueue
- LinkedBlockingDeque
- LinkedBlockingQueue
- LinkedList
- PriorityBlockingQueue
- PriorityQueue
- SynchronousQueue
You can use any of above based on your requirement to initiate a Queue object.
answered Apr 28, 2011 at 4:46
Harry JoyHarry Joy
58.5k30 gold badges161 silver badges207 bronze badges
Queue is an Interface not a class.
answered Apr 28, 2011 at 4:44
Andrew LazarusAndrew Lazarus
17.9k2 gold badges34 silver badges52 bronze badges
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>();
.
answered Apr 28, 2011 at 4:47
Jugal ShahJugal Shah
3,5811 gold badge24 silver badges35 bronze badges
You can use
Queue thequeue = new linkedlist();
or
Queue thequeue = new Priorityqueue();
Reason: Queue is an interface. So you can instantiate only its concrete subclass.
answered Oct 21, 2014 at 12:08
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 :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();
answered Dec 23, 2020 at 15:33
BaddaBadda
1,3192 gold badges14 silver badges39 bronze badges

Today, we will learn how to fix the error cannot instantiate the type error
in Java.
This type of error occurs when you try to make an instance of an abstract class. Let’s learn a bit about abstract classes in Java.
Fix cannot instantiate the type
Error in Java
We usually use an abstract class when we need to provide some common functionalities among all its components. You’ll be able to implement your class partially.
You will be able to generate functionalities that all subclasses will be able to override or implement. However, you cannot instantiate the abstract class.
Look at the following code:
abstract class Account
{ // abstract class Cannot Be initiated...
private int amount;
Account()
{
//constructor............
}
public void withDraw(int amount)
{
this.amount = this.amount - amount;
}
}
The above abstract class Account
cannot be instantiated. Meaning you cannot write the following code.
Account acc = new Account(); // Abstract Cannot Intialized......
So, what’s the solution? You can create a concrete/child class of this abstract class and make an instance of that.
For instance, there are so many types of accounts. They could be savings, business, debit, and much more.
However, all of them are actual accounts, and that is something that they have in common. That’s why we use abstract methods and classes.
Take a look at the following code.
class BusinessAccount extends Account
{
private int Bonus;
public void AwardBonus(int amount)
{
this.Bonus = Bonus + amount;
}
}
BusinessAccount
class is a concrete and child class of the abstract Account
class. You can make an instance of this class and get your work done.
BusinessAccount bb = new BusinessAccount();
//Bussiness Account Can Be intiated Because there is concreate defination..........
So, the conclusion is that you cannot instantiate the abstract class; instead, you can create its child class and instantiate it for the same functionality.
The following is a complete code that you can run on your computer.
abstract class Account
{ // abstract class Cannot Be intiated...
private int amount;
Account()
{
//constructor............
}
public void withDraw(int amount)
{
this.amount = this.amount - amount;
}
}
class BusinessAccount extends Account
{
private int Bonus;
public void AwardBonus(int amount)
{
this.Bonus = Bonus + amount;
}
}
public class Main {
public static void main(String[] args)
{
//Account acc = new Account(); // Abstract Cannot Intialized......
BusinessAccount bb = new BusinessAccount();
//Bussiness Account Can Be intiated Because there is concreate defination..........
}
}
To learn more about Abstract Class, click here.
The InstantiationException
is a runtime exception in Java that occurs when an application attempts to create an instance of a class using the Class.newInstance()
method, but the specified class object cannot be instantiated.
Since the InstantiationException
is an unchecked exception, it does not need to be declared in the throws
clause of a method or constructor.
What Causes InstantiationException
The InstantiationException
is thrown when the JVM cannot instantiate a type at runtime. This can happen for a variety of reasons, including the following:
- The class object represents an abstract class, interface, array class, primitive or
void
. - The class has no nullary constructor. Such a constructor is required when a parameterized constructor is defined for the class.
InstantiationException Example
Here is an example of an InstantiationException
thrown when the Class.newInstance()
method is used to create an instance of a boolean
:
public class InstantiationExceptionExample {
public static void main(String[] args) {
try {
Class<Boolean> clazz = boolean.class;
clazz.newInstance();
} catch (InstantiationException ie) {
ie.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
Since boolean
is a primitive data type, a new instance of it cannot be created using the Class.newInstance()
method, which can only construct objects for concrete classes. Running the above code throws the following exception:
java.lang.InstantiationException: boolean
at java.base/java.lang.Class.newInstance(Class.java:598)
at InstantiationExceptionExample.main(InstantiationExceptionExample.java:5)
Caused by: java.lang.NoSuchMethodException: boolean.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3427)
at java.base/java.lang.Class.newInstance(Class.java:585)
... 1 more
How to Resolve InstantiationException
To avoid the InstantiationException
, it should be ensured that the instance of the class that is attempted to be created at runtime using Class.newInstance()
is a concrete class and not an abstract class, interface, array class, primitive or void.
If it is a concrete class, it should be ensured that the class has a nullary constructor (in case it contains a parameterized constructor). If this is not possible, the Constructor
objects can be reflectively looked up and used to construct a new instance of the class using Constructor.newInstance(args)
with arguments that pass the actual constructor argument values.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever.
Sign Up Today!
posted 3 years ago
-
1
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Welome to the Ranch
You have provided lots of useful information, more than some people do, but I can’t just offhand see the cause of your problem. Let’s try reformatting your code because your lines are so long that I can’t read them as one piece:-. . . That’s a bit better,, but there are still things to improve.
Don’t use so many empty lines. If you want to separate paragraphs use one empty line.
Be more consistent with where you haev spaces. Don’t write a space after ( but do put a space after a
<
or every comma.
Only use // comments for something very short, or for commenting‑out. For anything longer, use /* comments */
Call a method returning a
boolean
something different; you should write
isOccupied()
rather than
getOccupied()
; Eclipse can change that for you with its refectoring capabilities.
The old Sun style guide suggests, don’t use that
if‑else
in your lines 22‑26; Write:-Yuo will also find a section in the same style guide about line lengths.
Don&apost use tabs for indenting; get Ecipse to convert a tab to four spaces automatically.
There is something iffy about your casting those numbers to a
char
and I don’t think it will do what you want. Don’r hard‑code 65, which is error‑prone. If you have to hard‑ode anything, use
‘A’
. That will give you floors starting at B, and strange floor numbers if you have more than 25 of them.
It is not obvious what ariables called
s
and
c
mean.
The
>
which appeared mysteriously in line 19 is probably a problem with our forum software.
Your
setOccupied()
method is written incorrectly; it won’t do what you want.
I don’t like the overloaded constructors, particularly if you pass small
int
s which get cast to control characters or
n
or similar.
I still can’t see why line 28 won’t compile. I don’t like the look of line 58. Nor did the compiler. You are missing () in line 65, but I still can’t see how you are getting that error in line 28.
I am getting this strange error and I cannot for the life of me figure out why:
Cannot instantiate the type Image
CODE:
import java.awt.Image;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class MainMenuState extends BasicGameState {
int stateID = -1;
Image background = null;
Image startGameOption = null;
Image exitOption = null;
float startGameScale = 1;
float exitScale = 1;
MainMenuState( int stateID )
{
this.stateID = stateID;
}
public int getID() {
return stateID;
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
try {
background = new Image("data/menu.jpg");
Image menuOptions = new Image("data/menuoptions.png");
startGameOption = menuOptions.getSubImage(0, 0, 377, 71);
exitOption = menuOptions.getSubImage(0, 71, 377, 71);
}catch (SlickException e) {
System.err.print(e);
}
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
}
}
Why do I get this error? I’ve googled endlessly and nobody else has it, this worked fine in my other game. Any ideas?