Static Importers and Constructors

In Java, if I want to use a method without instantiating an object of a particular class, I use static import.

Something like:

import static com.company.SomeClass.*; 

Then I can call methods from this class in another class without creating an instance of SomeClass.

As soon as I use a method from this class, is it also a constructor from this class?

For example, if I call

 SomeClass.doStuff(); 

Does the constructor for SomeClass get called backstage?

+7
java constructor import static
source share
3 answers

Does the constructor for SomeClass get called backstage?

The method call does not call the constructor. The constructor is called when the class is instantiated. Here you do not create an instance of SomeClass , but simply access the static method directly by the name of the class. Thus, it makes no sense to call the constructor.

However, if you want to call an instance method, you will first need an instance of the class containing this method. You can access the instance method only with the instance of the class. But in this case also the method call does not call the constructor behind the scene.

+3
source share

static import has nothing to do with what you are talking about. It just ensures that using

import static org.junit.Assert.assertEquals

you can use assertEquals() instead of Assert.assertEquals()

when you have the following signature:

 public class Assert { public static bool assertEquals() } 

Other than this: no, you do not call the constructor when using the static method. See @Rohit for clarification on this.

0
source share

Constructors are only called when new MyClass() or Class.newInstance . You can write some static block in this case.

0
source share

All Articles