Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
foobar5512 Avatar asked Aug 25 '13 20:08

foobar5512


People also ask

What do you mean by static import?

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.

Can we use static with constructor?

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.

What is static import explain with example?

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.

What is the difference between import and static imports?

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.


1 Answers

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.

like image 80
Rohit Jain Avatar answered Oct 21 '22 11:10

Rohit Jain