小程序中存在构造函数会引发异常
我正在运行下面的小程序。在其中,当我添加构造函数(甚至为空)时,小程序会引发运行时异常:
MainFrame.class can't be instantiated, java.lang.InstantiationException
如果我删除构造函数,则不会引发异常。小程序中不能有构造函数吗?
public class MainFrame extends JApplet implements WindowListener, ActionListener {
public void init()
{
System.out.println("Applet Step1");
String[] args = null;
createAndShowGUI(args);
}
private static void createAndShowGUI(String[] args) { /*code*/ }
public MainFrame(final String[] args) {}
}
I'm running the below applet. In it, the moment I add the constructor (even empty), the applet throws a runtime exception:
MainFrame.class can't be instantiated, java.lang.InstantiationException
If I remove the constructor, no exception in thrown. Can't I have a constructor present in an applet?
public class MainFrame extends JApplet implements WindowListener, ActionListener {
public void init()
{
System.out.println("Applet Step1");
String[] args = null;
createAndShowGUI(args);
}
private static void createAndShowGUI(String[] args) { /*code*/ }
public MainFrame(final String[] args) {}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还需要添加默认构造函数......
You need to add a default constructor too...
您需要一个默认构造函数,因为您的类的实例将由浏览器本身实例化(或浏览器将此任务委托给 jre 的 appletviewer 或插件)。
由于浏览器对您的类一无所知,因此它对所有 Applet 类起作用的唯一方法是使用一组标准参数实例化它们。而且,对于小程序来说,这组参数很简单:一个空集。
因此,您的类中需要有一个默认(不带参数)构造函数。
之后,@Rocky Triton 是对的:在java中,如果你没有在类中提供任何构造函数,java将为它提供一个默认构造函数。但是一旦你提供了一个构造函数,无论它是什么,java就不再提供默认的构造函数(正如你所说,在某种程度上,你开始对你的类的实例化负责)。
因此,在您的情况下,如果您决定提供带参数的构造函数,java将不会提供默认构造函数,并且浏览器将无法实例化您的类。
问候,
史蒂芬
You need a default constructor as instances of your class are going to be instanciated by the browser itself (or the browser delegating this task to jre's appletviewer or plugin).
As the browser doesn't know anything about your class, the only way for it to work on all Applet classes is to instanciate them with a standard set of parameters. And, for applets, this set of parameters is simple : an empty set.
So, you need to have a default (without params) constructor in your class.
And after that, @Rocky Triton is right : in java, if you don't provide any constructor in a class, java will provide it with a default constructor. But as soon as you provide a constructor, whatever it is, java doesn't provide the default constructor anymore (as you are saying, in some way, you become responsible for the instanciation of your class).
So, in your case, if you decide to provide a constructor with parameters, java won't provide a default constructor, and the browser won't be able to instanciate your class.
Regards,
Stéphane
我相信你也应该能够改变:
public MainFrame(final String[] args) {}
到:
public MainFrame(String... args) {}
这允许您不需要传入 args,因此它会构造它。
I believe you should also be able to change:
public MainFrame(final String[] args) {}
to:
public MainFrame(String... args) {}
This allows that you dont need to pass in args so it will construct it.