Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to write a constructor which does nothing?

To use methods of a class I need to instantiate a class. At the moment the class has not constructor (so I want to write it). But than I have realized that the constructor should do nothing (I do need to specify values of fields).

In this context I have a question if it is OK to write constructor which does nothing. For example:

public Point() {
}
like image 314
Roman Avatar asked Mar 08 '10 21:03

Roman


People also ask

Can constructor be empty?

Having an empty constructor (whether static or not) in a class is redundant, and ReSharper issues a warning to that effect. In the above, an empty static constructor is, in fact, a necessary detail that guarantees lazy initialization.

What are the rules for writing constructors?

The two rules for creating a constructor are: The name of the constructor should be the same as the class. A Java constructor must not have a return type. Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.

How do you write an empty constructor?

Empty constructor build GENERIC object, and constructor with parameters build objects with more specific information. Let's say the example above, if I create an instance object using the empty constructor: Person p1 = new Person(); -- it will still create an object but without any properties in it?

What happens if you don't write a constructor?

Constructors are called by the compiler automatically; they are rarely called explicitly by the programmer. If you write no constructor, the compiler will provide your class with a default constructor. The mechanism is suppressed once you write any constructor.


2 Answers

You don't need to write an empty contstructor; the Java compiler will automatically insert one for you (only if you haven't defined any other constructors that take some args).

So it's quite okay (and useful in some situations) but it's not required.

like image 182
Noon Silk Avatar answered Sep 29 '22 12:09

Noon Silk


It sounds like you are explicitly creating a default constructor which there is no need to do. The Default Constructor is automatically created if there are no other constructors.

like image 28
Matt Dearing Avatar answered Sep 29 '22 12:09

Matt Dearing