Main method empty? - java

I have a class that implements Runnable, but Eclipse needs a public static void main method in it. Is it ok if the main is completly empty?
public class Launcher implements Runnable{
private String message;
public Launcher(String message) {
this.message= message;
}
public static void main(String[] args) {
}
#Override
public void run() {
//My implementations
}

If you intend Launcher to be the main class of the application, the one you use to start it, the main method is needed and must do whatever should be done to start work.
If not, delete the main method. Eclipse does not require a main method unless you start the application by telling it to run the class. It will optionally generate one when creating a class, but that can be edited out if not needed.

No, the main method is the only method the compiler is searching for when looking where to start. Hence if you're main method is empty, nothing gets executed. At the very least add:
new Launcher("some string").run();
in the main method.

Related

Can we create an object of the class in which main function is defined in Java?

Is it possible to create object of class in which main method resides.I have been searching for this answer but I have been told that it depends on compiler some compiler will allow while others will not.Is that true?
Yes? The main method is just an entry point. The class is like any other, except it has an additional public static method. The main method is static and therefore not part of the instance of the object, but you shouldn't be using the main method anyway except for starting the program.
public class Scratchpad {
public static void main(String[] args) {
Scratchpad scratchpad = new Scratchpad();
scratchpad.someMethod();
}
public Scratchpad() {
}
private void someMethod() {
System.out.println("Non-static method prints");
}
}
Yes, you can create object for the class which has main method. There is no difference in this class and a class which don't have main method with respect to creating objects and using.

what is the difference in the behavior of this code?

I have the following code:
public class Application extends ApplicationManager{
public static void main(String[] args) {
ProcessUtility.enableProcessUtility();
new Application().start();
}
}
and the class ApplicationManager code:
public class ApplicationManager {
public ApplicationManager() {
String configPath = "file:home" + File.separator + "log4j.xml";
System.setProperty("log4j.configuration", configPath);
logger = Logger.getLogger(ApplicationManager.class);
}
protected void start() {
logger.info("*** Starting ApplicationManager ***");
}
when I run the application class the start method of the parent will be called, can it be called without calling the parent default constructor?
my second question is the above code different from this code:
public class Application extends ApplicationManager{
public static void main(String[] args) {
new Application().start();
}
#Override
protected void start() {
ProcessUtility.enableProcessUtility();
super.start();
}
}
and the ApplicationManager class as above.
this is the code of the static method:
public static void enableProcessUtility() {
isCommon = false;
}
thanks in advance.
Calling a non static method (your start method) requires creating an instance of the class that contains the method (or a sub-class of that class). Creating an instance of a class requires invoking the constructors of the class and all its ancestor classes. Therefore you can't avoid executing the parent default constructor.
As for the second question, moving ProcessUtility.enableProcessUtility() to the sub-class's start method means that it will be executed each time you call the start method.
That said, in your example your main only creates one instance of Application and only calls start once for that instance. Therefore ProcessUtility.enableProcessUtility() will only be executed once in both snippets, and the behavior would be identical.
EDIT: Another difference between the two snippets is that the first snippet calls ProcessUtility.enableProcessUtility() before creating the Application instance, while the second snippet first creates the instance and then calls ProcessUtility.enableProcessUtility() from within start of the sub-class. If the behavior of the constructors (of either the sub class or the super class) is affected by the call to ProcessUtility.enableProcessUtility(), the two snippets may produce different outputs.
Your first question is answered here https://stackoverflow.com/a/10508202/2527075
As for your second question, the super constructor will be called before the ProcessUtility call in the second example, where in the first example the ProcessUtility call comes first.

Calling main inside the code

Can we call main() function inside any other function? I tried but did not come up with it.
If we can't call it then why?
Why main() is not like ordinary methods?
Yes why not try something like:
public class Main {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
public class NewMain {
public static void main(String args[]) {
Main.main(args);
}
}
If you run:
java NewMain
the output is:
Hello World
Why main() is not like ordinary methods
Not like ordinary methods in what sense? It is like any other method. I'll try to explain why main looks like this, maybe it'll help you to understand what's going on.
It's void because when it finishes, it doesn't mean that the program finished. If it spawns a new thread it might be that these threads are still running.
It's public because it's called by the JVM, which is outside the scope of the project.
And of course it has to be static because when the JVM calls it, there's no object existing for the class being called.
Nothing special about it when you understand it, so yes.. it can be called like any other static method.
Sure you can, main() is like nay other method in that area.
public class A {
public static void main(String[] args) {
System.out.println("a's main()");
B.main(new String[0]);
}
}
public class B {
public static void main(String[] args) {
System.out.println("B's main()");
}
}
Running A's main() will produce:
a's main()
B's main()
All the actions that you do one other methods can also be done on the main method
The only difference between main method and other methods is that the main method servers as the starting point for running a class
The java command launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
Except for this reason, there is nothing else.

Extending the main class in Java

I need to extend the functionality of my main class, by overriding some of its methods. I was expecting that the class extending the main class would be able to be run. However, Eclipse doesn't recognize MyLauncher as a runnable class. In the following code, I have a setup() method that is overridden by the subclass. What I want is a way to run the main(..) from the super class but also the setup from the subclass.
// Launcher.java
public class Launcher {
Launcher instance;
public static void main (args[]) {
instance = new Launcher(); // This is likely the problem
instance.setup();
}
public void setup() {
System.out.println("Default agent setup.");
}
}
// MyLauncher.java
public class MyLauncher extends Launcher {
public void setup() {
System.out.println("New agent setup!");
}
}
I accept alternatives to this. I can't add a main method to the subclass, though. The Launcher class is inside an API i'm making, so it can't refer to the class MyLauncher that is using the API.
edit: I think this is to specific to my problem. I decided to search for a new approach. Since I'm working with JDT, I'm going to parse the Launcher and inject the class.
Static methods are not inherited, they're always bound to the class that defines them, and need to be called explicitely.
In you case, the MyLauncher needs a main() method too, and could then delegate to the main() method of Launcher:
public class MyLauncher extends Launcher {
public static void main (String[] args) {
Launcher.main(args);
}
protected void setup() {
System.out.println("New agent setup!");
}
}
Protected methods can not be called from outside. So the MyLauncher.setup() do not override Launcher.setup() and instance.setup(); calls the public method from Class Launcher.
There can only be one main method in your project, that is one entry point to the program. So let's assume you're going to be keeping the main method in the Launcher class.
Your main method signature should be:
public static void main (String args[])
And unless you want the setup() method from the launcher to be called you'd want to do:
instance = new MyLauncher();
That would call the setup() method from MyLauncher.
If you want to call setup() from the Launcher class you need to instantiate the launcher class:
instance = new Launcher();
If you want to be able to run MyLauncher.setup(), the variable must be a MyLauncher. You are initializing and storing a Launcher in the main() function.
If the two classes are in the same package, or Launcher.java imports the MyLauncher class, then the main() function in Launcher should be able to be:
public class Launcher {
Launcher instance;
public static void main(String[] args) {
instance = new MyLauncher();
if(instance instanceof MyLauncher) {
((MyLauncher) instance).setup();
} else
{
instance.setup();
}
}
}
As you say, the fact that you create an instance of Launcher directly in main means that no inheritance is available. Even if you could start MyLauncher easily from Eclipse, within the main method you wouldn't know which type had actually been used to start it. I can't see any easy solution that doesn't involve either creating a main method in each class or providing the class name as a command-line argument. I would probably separate the "running" from anything else:
public class Launcher {
public static void launch(LaunchConfiguration configuration) {
configuration.setup();
...
}
}
public class LaunchConfiguration {
public static void main(String[] args) {
Launcher.launch(new LaunchConfiguration());
}
public void setup() {
}
}
public class MyLaunchConfiguration {
public static void main(String[] args) {
Launcher.launch(new MyLaunchConfiguration());
}
#Override
public void setup() {
}
}

Calling main method class from another java class

I have two java classes.One in which my GUI is written and the other class in which i have implemented an interface(call it class 2).My project starts from the main method of GUI.I want to send a string to my GUI class from the class 2 for displaying it in the Text area but nothing is happening.
As my main gui class is
public class GraphicalInterface extends javax.swing.JFrame{
//I have created a function over here for displaying string in text area
public void show1(String name)
{
jTextArea1.setText(name);
}
//buttons code
public static void main(String args[]) {
//code
}
}
I have created an object of this class in my class 2 like below
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
Please help me out that how can i call main method class from another java class.Thanks.
You may be trying to call this code outside of a constructor or method (or initializer block) and in Java, this can't be done. Instead call this code inside of a method or constructor.
I guess that you have a design problem in your project. Let me expain. You say you have a GUI class "GraphicalInterface" which holds the main method which is the starting point of an application in Java. You say you need to call the main method of this class in another class,
"your class 2". If so why isn't the place belonging to the "main method" of your application in which you try to call this GUI's main method. Call GUI's main method x(), let the place that you call x() belong to the main method.
If you need to operate on the GUI's fields in another classes and also keep the main method still there, then I suggest you to apply Singleton Pattern to your GUI class. In that way you
will be able to refer the only instance of your public singleton class everywhere in your application.
public class GraphicalInterface extends javax.swing.JFrame
{
public String textAreaContent;
public getX()( return textAreaContent;)
public setX(String s)( this.textAreaContent = s;)
public void show1()
{
jTextArea1.setText(this.getTextAreaContent());
}
public static void main(String args[])
{
//code
}
}
From your other class:
GraphicalInterface b=new GraphicalInterface();
b.setX("text area content");
b.show1();
No, the best solution is not to do this, and if you feel you must, it is likely because your design is somehow broken. Instead write your code so that your classes are true OOPs classes that interact in an intelligent way (low coupling, high cohesion), and to only need one main method.
Also, you state:
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
What do you mean by "it does not allow me to write this statement"? Does the Java compiler give a compilation error? Does the JVM throw an exception? Does the JVM reach out of your monitor and slap you in the face? Please let us know all the details necessary to be able to help you.
You need to create a method in class2 and call it from your main method.
Sample code class1
public class Test1 {
public void show(String ab){
System.out.println(ab);
}
public static void main(String[] args) {
Test2.Test2();
}
}
Above code i create a class Test1.java like your class1 and create a method with one parameter and call it from class2 method.
Sample code class2
public class Test2 {
static void Test2(){
new Test1().show("Pass String to class1 show method");
}
}
here you can pass your string value.

Categories