Presence of constructor in an applet throws exception
I'm running the below applet. In it, the moment I add the constructor (even开发者_如何学JAVA 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) {}
}
You need to add a default constructor too...
public MainFrame() {}
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
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.
精彩评论