3

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) {}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191

3 Answers3

6

You need to add a default constructor too...

public MainFrame() {}
Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
  • 2
    Because as soon as you add a constructor to your class, you lose the default constructor. The default constructor is automatically created by java UNLESS there is another constructor present. – Rocky Pulley Jun 22 '11 at 17:53
  • 1
    is right about constructors. But it's not a good explanation of *why* you need a default constructor here. Can you post the error you received ? – Snicolas Jun 22 '11 at 17:58
  • 2
    The reason he got the error was because the browser tries to instantiate his applet by basically calling "new MainFrame();" But that constructor no longer exists, which is why he gets an InstantiationException. – Rocky Pulley Jun 22 '11 at 18:00
3

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

Snicolas
  • 37,840
  • 15
  • 114
  • 173
0

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.