Why do applets not need a main()?
Asked Answered
E

5

11

This applies to subclasses of Applet, Servlet, Midlet, etc.

Why do they not need a main()? If I wanted to create a Craplet class that starts at init() or something similar, is it bad design, or how would I go about doing it?

Escudo answered 31/5, 2009 at 13:27 Comment(0)
C
17

It is actually good design but not obvious and what you want to do would have no effect so it is a little counter intuitive.

These types of applications live their lives in containers and as such their entry points are determined by the standards those containers must adhere to. The designers of these standards chose not to call the entry point main. You would place your functionality in an overridden method. All applets have the following four methods:

public void init();
public void start();
public void stop();
public void destroy();

They have these methods because their superclass, java.applet.Applet, has these methods.

The superclass does not have anything but dummy code in these:

public void init() {}

If you want to derive a class to extend or change the name of init() you should Implement your class and have your method call init(). This would use polymorphism to let you call the method whatever you like. Unless you are writing servlet container you are likely wasting your time.

Chocolate answered 31/5, 2009 at 13:37 Comment(0)
E
12

Applets and Servlets do not start their own process. Instead they run inside a container. Therefore, they do no need a static main method (which starts the process), but a way to interact with their container.

Embed answered 31/5, 2009 at 13:34 Comment(0)
U
3

'main' is just a convention that C, C++ and java commonly support, but for example, if you write C or C++ directly against the Win32 API, you don't have to have main(), but instead you have WinMain.

Uzial answered 31/5, 2009 at 13:37 Comment(2)
I have beefs with its just a convention but +1 for true... I get so mad when names are the best choice... why didn't they name it main without arguments?Chocolate
At least WinMain had some reference to being an entry point. But I suppose it is different because WinMain was actually in charge and not a slave. I guess you are right.Chocolate
B
2

The executing environment of an applet (typically, your web browser) calls the applet methods at different points depending on what stage of rendering the it's reached. That provides a level of abstraction that's better suited for the web than a simple main() method. Further, launching arbitrary Java programs with main() methods would usually be considered something of a security risk.

Breadstuff answered 31/5, 2009 at 13:36 Comment(0)
H
0

Applet do not use main() because when applet is loaded it automatically calls certain methods of applet class to start and executes the applet code. and applet have its own life cycle.

Heurlin answered 17/10, 2014 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.