Presence of constructor in an applet throws exception

拥有回忆 提交于 2019-12-12 14:52:03

问题


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) {}
}

回答1:


You need to add a default constructor too...

public MainFrame() {}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/6444253/presence-of-constructor-in-an-applet-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!