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
  • 100,966
  • 191
  • 140
  • 197
  • 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
  • 85,357
  • 5
  • 51
  • 72
-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
  • 512
  • 1
  • 6
  • 19
  • @rzwitserloot This is not misleading, its just another approach. – Ankit Gupta Jul 30 '20 at 12:16
  • ... I'd say writing code that goes against every style guide in existence and literally every linter for java on the planet counts as a particularly bad answer then, Ankit. This is _not_ a good idea. – rzwitserloot Jul 30 '20 at 12:18
  • @rzwitserloot I made a correction in the answer, its not "Your static methods.." – Ankit Gupta Jul 30 '20 at 12:20
  • 1
    this is a singleton pattern and could (imho) also be used in this case. https://en.wikipedia.org/wiki/Singleton_pattern – roediGERhard Jul 30 '20 at 12:29