Hutch
Hutch

Reputation: 63

Why instantiate main class when you can use static?

My friend is new to programming. He said he had a problem in his code and shared his screen on Skype. I saw he had instantiated his Main class to use all the functions, etc. It looked like this:

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

I've also noticed this in a couple tutorials online. The thing is, since you shouldn't really have more than one main, why instantiate it?

Upvotes: 4

Views: 1251

Answers (4)

Hiren
Hiren

Reputation: 51

The static methods can be easily accessed with the following format. ClassName.methodname(). But instance method of the class can not be called without creating. If we have all the methods static, in that case there is no need of the the creation of the objects as we do it in utility classes.

Upvotes: 1

zapl
zapl

Reputation: 63955

You could argue that it's better that way.

You should probably not have a Main class to begin with but one with a proper object oriented purpose that encapsulates something.

The main method has to be unfortunately inside one of your classes. But that doesn't mean that the poor class that has to house the main method isn't allowed to be instantiated.

In pure OOP there is no place for static at all. Not even utility classes: http://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html

Upvotes: 3

Ryan
Ryan

Reputation: 1974

The difference between using static and non-static context can be found here

Assuming your asking why he would create a object of his main class the answer would be to access non-static methods from within static context. Without that main class object, he would only be able to access static methods and classes. I would recommend looking into Object Oriented Programming basics, which can be found here.

 Main main = new Main(); //creates object of class Main
 main.Example(); //calls method Example from object main

What your friend did was create a instance of the class and store it into memory. He is not instantiating the main method, but the class Main. This gives him the ability to alter information belonging to his main object of the class Main.

The purpose for doing this is to access non-static methods in the class Main.

Upvotes: 1

ThisaruG
ThisaruG

Reputation: 3412

This code initialize the Main class. Not public static void main() method !!!

It is a common thing in Java as per my knowledge as you can't always use static classes or methods.

you cannot access non-static variables or methods inside static methods (like main method). Hence the way to do is to create an instance of the class itself and use non-static variables or methods.

Refer this question

Upvotes: 1

Related Questions