0

I am on my way of learning JAVA, and the more I learn, the more I realise how much I don't know. I am having trouble understanding object initialisation in details. (I didn't paste the whole code for the simplicity's sake). Thank you in advance.

I have a GUI class which creates the GUI, and I have a driver class called Calculator with the Main() method in it. My program works well, I just want to understand object initialisation in details, because I am a bit confused.

public class GUI {

    GUI() {

    }

    public static void Init() {

    // Code for creating GUI and elements   

    }

}
public class Calculator {

    public static void main(String args[]) {

        GUI main = new GUI(); // Option 1
        new GUI; // Option 2 
        GUI.Init(); //Option 3
    }

}

So my question is if I have a class with a no-arg constructor or constructor with data, what is the best approach to run the program? What is the best practice? Which approach should I use?

My understanding is:

GUI main = new GUI(); // This will initiate the object, but will not execute

new GUI; // This will initiate and execute my program and run

GUI.Init(); // This will run the method of GUI, therefore can be used to run the program if built that way.

ficsorr
  • 13
  • 1
  • For creating the instance, all three ways end up using/beeing your 2nd option. Now creating an instance doesn't run anything and all three options you gave turn out to not running anything(or well creating your instance and then exit the program. – kai Feb 14 '19 at 02:35

2 Answers2

0

The standard thing would be for init (lower case for proper style) to not be a static method and for it to be run as follows:

GUI main = new GUI();
main.init();

You create the object and then call its method. This allows for real object-oriented programming. In this paradigm, only your driver should be static, and then it should create the objects that it needs and use them.

Otherwise you just get a cascade of static methods calling other static methods and that defeats the purpose of object-oriented programming.

GenTel
  • 1,448
  • 3
  • 13
  • 19
0

The approach to be taken here purely depends upon your requirement. If you really don't require an object to invoke your function (ie: If you don't need to set values for any variables) then option3 would be a good choice.

The below posts may help you understand more on these concepts. https://stackoverflow.com/a/2671636/6761121

https://www.baeldung.com/java-initialization

Leo Varghese
  • 165
  • 1
  • 2
  • 12