Saathvik
Saathvik

Reputation: 279

Are constructors in Java static in nature or non-static in nature?

There is a similar question Constructor is static or non static

But few answers tell that constructor is static and few tell that constructor is non-static. This is confusing. So can anyone please clarify whether constructor is static in nature or non-static in nature?

Upvotes: 2

Views: 286

Answers (2)

Alexey Soshin
Alexey Soshin

Reputation: 17691

I'm not sure which answer got you confused. But in Java, constructors aren't static.

See the following example:

public class MyTest {
    public static void main(String[] args) {
        new Test(); // Prints reference within the constructor
        new Test(); // The reference is different here
    }
}

class Test {
    public Test() {
        System.out.println(this.toString());
    }
}

As you can see, by calling constructor twice, you get two different references to the object. This means that context of the constructor is not static.

You may have factory methods in your class, which are static and create instances:

class Test {

// May be called like Test.create() and returns instance
public static Test create() {
    return new Test();
}

But inside those methods, you'll still have to call class constructor. Which is, as I demonstrated earlier, is not static.

Upvotes: 1

JRG
JRG

Reputation: 4177

This is what Java Specification says about constructors, in §8.8.3. Constructor Modifiers:

Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized:

  • A constructor is not inherited, so there is no need to declare it final.

  • An abstract constructor could never be implemented.

  • A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static.

  • There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work.

  • The lack of native constructors is an arbitrary language design choice that makes it easy for an implementation of the Java Virtual Machine to verify that superclass constructors are always properly invoked during object creation.

  • The inability to declare a constructor as strictfp (in contrast to a method (§8.4.3)) is an intentional language design choice; it effectively ensures that a constructor is FP-strict if and only if its class is FP-strict (§15.4).

Upvotes: 4

Related Questions