1

I was wondering if there is any benefit of this

public static main(String[] args)
{
    Main mainInstance = new Main();
    mainInstance.Foo();
}

public void Foo() {}

over this

public static main(String[] args)
{
    Foo();
}

public static void Foo() {}

The one am used to is the second example, but I came across a piece of code that's like the first example, and am curious to know if it has any benefits over the other

2
  • curious to know if it has any benefits over the other - what things can you think of by yourself? Commented Feb 4, 2020 at 6:41
  • Well, it depends what Foo actually does, but if it uses any of the data stored inside instances of the class, then it will need to be an instance method. Commented Feb 4, 2020 at 6:42

2 Answers 2

2

In a trivial example (like your sample), there is no difference.

More generally, I can think of two advantages in the first approach over the second:

  1. Assume that the foo methods and others make use of information held in fields of the enclosing class. If the methods are static, then the fields need to be static as well. It is a well established fact that static variables make unit testing difficult. The first approach avoids this problem, both for testing main and the other methods.

  2. Assume that the functionality provided by the enclosing class (Main) is non-trivial, and you want to be able to reuse it. If you structure your code like this:

    public class Main {
    
        public static main(String[] args) {
            Main main = new Main();
            // parse 'args' and set config parameters in 'Main' fields 
            main.doIt();
        }
    
        public void doIt() {
            ...
        }
    }
    

    then you can use the functionality of main in other ways. For example, you could use it like this:

    Main.main(new String[]{"arg1", "arg2"});
    

    or like this:

    Main m = new Main();
    m.setConfigParam1(...);
    m.setConfigParam2(...);
    m.doIt();
    

    Using an instance and instance fields gives you more flexibility.

Whether these are significant or not will depend on the context.

0

Static methods/variables are stored in the static memory. They are always there in the memory even if these methods/variables are not used once. So if there is some code that is using large memory, it is not advisable to declare them as static. On the other hand if some method/s are called rarely during whole execution process, and are not dependent on state of object, it can be declared as static. This will save the memory for declaring object, its class variables, etc..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.