Static Imports and Constructors

In Java, If I want to use a method without creating an instance object of a specific class I use static imports.

Something like:

import static com.company.SomeClass.*;

I can then call methods from that class in aother class without creating an instance of SomeClass.

Once I use a method from that class, is the constructor from that class called as well?

For example, if I call

SomeClass.doStuff();

Does the constructor get called for SomeClass behind the scenes?


Does the constructor get called for SomeClass behind the scenes?

Invoking a method doesn't call constructor. Constructor is called when you create an instance of a class. Here, you aren't instantiating the SomeClass , but simply accessing the static method directly on class name. So, there is no point of constructor being called.

However, if you want to invoke an instance method, then first you would need an instance of the class containing that method. You can access an instance method only using an instance of class. But in this case also, calling the method doesn't call constructor behind the scene.


static import hasn't got anything to do with what you're talking about. It just makes sure that with

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 that: no, you do not invoke the constructor when using a static method. Refer to @Rohit's answer for clarification on this aspect.


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

链接地址: http://www.djcxy.com/p/15416.html

上一篇: iOS AudioSessionSetActive()阻止主线程?

下一篇: 静态导入和构造函数