TheCodeIntel
TheCodeIntel

Reputation: 21

In Java, is constructor non static?

Many people say that constructor in java is Non-static..! To initialize object we need Constructor. Therefore, we can use constructor without object then Constructor must be static.

Upvotes: 0

Views: 92

Answers (5)

ring bearer
ring bearer

Reputation: 20773

In Java constructor can not be static or synchronized. An object will be constructed(creation+initialization) only by one thread at a time and constructor is run on already created instance - meaning in a non-static context.

Upvotes: 0

Blip
Blip

Reputation: 3171

The constructor in Java is not use to construct an object, but to initialise the object. The constructor is the first method that is run by the JVM after the object is constructed of instantiated.

Upvotes: 0

Rajesh
Rajesh

Reputation: 2155

Static members should be invoked with the class name, without the need for creating an instance of the class, as in

ClassName.memberName/(..)

See good explanation :Java static constructor – Is it really Possible to have them in Java?

Upvotes: 1

Honza Zidek
Honza Zidek

Reputation: 19926

Well, it's not about what "many people think" but rather about the definition. As the Java Language Specification says:

An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

and

A method that is not declared static is called an instance method, and sometimes called a non-static method.

As you have this and super defined within the context of a constructor, you must consider the constructor as a non-static method, however I understand the idea behind your post that new bears some static features:

  • you call new before you have an instance ready
  • new is not virtual

Upvotes: 0

SLaks
SLaks

Reputation: 887305

A constructor has an instance (this is available). Therefore, it is, by definition, not static.

The JRE runs the constructor after it creates an instance.

Upvotes: 4

Related Questions