Java 返回错误“无法实例化类型”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30317070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java returns error "Cannot instantiate the type"
提问by Mohammad Nurdin
I got this error message when I try to init a new object.
当我尝试初始化一个新对象时收到此错误消息。
Cannot instantiate the type Car
My code
我的代码
Main.java
主程序
public class Main {
public static void main(String args[]){
Car car = new Car(4,4,COUNTRY.MALAYSIA, Locale.ENGLISH, "150.00"); //error here
}
}
Car.java
Car.java
public abstract class Car implements Automobile {
public int wheel;
public int door;
public COUNTRY country;
public Locale locale;
public String price;
public Car(int w, int d, COUNTRY c, Locale l, String p){
this.wheel = w;
this.door = d;
this.country = c;
this.locale = l;
this.price = p;
}
}
采纳答案by Kenneth Clark
Car is an Abstract class you cannot create an instance of it.
Car 是一个抽象类,你不能创建它的实例。
public abstract class Car implements Automobile
you can potentially do something like
你可以做类似的事情
public class FordFocus extends Car
keep in mind that you will need to call the super constructor, but then you will be able to create an instance of the FordFocus car type
请记住,您将需要调用超级构造函数,但随后您将能够创建 FordFocus 汽车类型的实例
回答by Abubakkar
Your class Car
is an abstract class and you cannot create an instance of an abstract class.
您的类Car
是抽象类,您不能创建抽象类的实例。
Solution 1
Instead you need to create a concrete class that extends your class Car
and then you can create an instance of that concrete class.
解决方案 1
相反,您需要创建一个扩展类的具体类,Car
然后您可以创建该具体类的实例。
Solution 2
Remove abstract from your Car
class declaration (But I think you don't want to do that).
解决方案 2
从您的Car
类声明中删除抽象(但我认为您不想这样做)。
回答by Naman Gala
Documentation
states that
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
抽象类是声明为抽象的类——它可能包含也可能不包含抽象方法。抽象类不能被实例化,但它们可以被子类化。
So reference Car car
is supported, but object new Car();
is not supported.
所以Car car
支持引用,但new Car();
不支持对象。