0

I am new to java, and I'm writing a GUI program. I have a class independent of the GUI whose methods I would like to use in the GUI class. The methods are static, and I would prefer to not have objects since they would serve no purpose. However for the code to fulfill its purpose, a piece of code needs to initially run, which seems to be impossible without a constructor. So is it possible to run said code without creating an instance of said class?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • 5
    You mean like with a [static initializer](https://stackoverflow.com/questions/2420389/static-initialization-blocks)? – Kayaman Jul 30 '20 at 12:11
  • You wrote in your question: _a piece of code needs to initially run, which seems to be impossible without a constructor._ Care to elaborate on how you arrived at that conclusion? – Abra Jul 30 '20 at 12:12
  • 1
    Does this answer your question? [Static Initialization Blocks](https://stackoverflow.com/questions/2420389/static-initialization-blocks) – Possenti Jul 30 '20 at 12:16

2 Answers2

1

You can make static initializers, which are run at most once ever for the lifetime of a JVM, and are run 'as needed' (not as your software starts, but the moment your code ever tries to touch the class, if it hasn't been initialized yet, it will get initialized at that point in time):

public final class WidgetOperations {
    private WidgetOperations() { /* prevent construction */ }

    static {
        System.out.println("Hello! I am initializing!");
    }

    public static void foo() {
        System.out.println("FOO");
    }
}

if you have this code:

void example () {
    WidgetOperations.foo();
    WidgetOperations.foo();
}

you would see:

Hello! I am initializing!
FOO
FOO
rzwitserloot
  • 65,603
  • 5
  • 38
  • 52
-1

Try this approach...

class Test{
     private static final Test instance = new Test();
     private Test(){//init code}
     
     public static Test getInstance(){
         return instance;
     }
   
     //Your methods..
}

Use the functions like..

Test.getInstance().function();
Ankit Gupta
  • 244
  • 1
  • 5
  • 17