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?
Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.
Java constructor can not be static One of the important property of java constructor is that it can not be static. We know static keyword belongs to a class rather than the object of a class. A constructor is called when an object of a class is created, so no use of the static constructor.
static import allows to access the static members of a class without class qualifications. For Example, to access the static methods you need to call the using class name: Math. sqrt(169); But, using static import you can access the static methods directly.
Difference between import and static import: With the help of import, we are able to access classes and interfaces which are present in any package. But using static import, we can access all the static members (variables and methods) of a class directly without explicitly calling class name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With