Search code examples
javanetbeanslwjgl

How do I avoid unnecessary class references in Java?


I have two java classes (.java files). I want to be able to create new instances of an object in one class that were defined in the other class, without referencing the class name each time. In C# there are #using and includes, but I am only able to use import <pre-compiled code> in java. Is there a way to do this:

import TestClass;

and then simply call a function inside it without using

TestClass.TestFunction()

every time? I simply need to have all of my functions and objects to be separate from my Main class.


Solution

  • Assuming TestFunction is a static method in TestClass, you can use a static import:

    import static TestClass.TestFunction;
    // or
    import static TestClass.*;
    

    and then call it without using the class qualifier:

    TestFunction(...);
    

    Note this can lead to confusing/hard-to-read code – use static imports sparingly.