Purpose of a Constructor in Java

Purpose of a constructor in Java?

Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object

From the official Java tutorial:

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

what's the point of java constructor?

Constructors are what you use to initialize/set up the instances of your classes.

If you have an object that needs some processing before it is usable (initializing members for instance), you should do that in the constructor.

Ideally, you should never have "partially built" objects (i.e. objects that are "live", that you hold a reference to, but that are not yet usable). Without constructors, you'd be permanently creating partially built objects, and that is very error-prone. (Theory and practice don't always match, but keep that idea in mind.)

What is the actual use of the default constructor in java?

The problem is that while you know the default constructor doesn't do anything in this example, in future the constructor might do something even if you don't realise it is and you might not be able to re-compile everywhere the code is used reliably. So the safest, simplest thing to do is to always call a constructor which might change in the future and let the JIT optimise away the constructor if it doesn't actually do anything.


The byte code always calls a contructor, whether you provide one or not. When you compile code which uses the default constructor it cannot assume the constructor doesn't do anything useful as you can add something to it later to do something useful. e.g.

Say you change

public class Test {
int a;

// public Test() { //this constructor does nothing
}

to

public class Test {
int a;
final List<String> strings = new ArrayList<>();

// public Test() { //this constructor does something now.
}

or

public class ServerTest {
final List<String> strings = new ArrayList<>();
}

public class Test extends SuperTest {
int a;
// the default constructor has to call super();
}

The constructor now initialised the strings field. You can change this class without having to re-compile everywhere it is used and say, hey, my constructor now does something useful, you should call it now.

What is the purpose of parameterized constructors?

That's for easily creating your class without needing extra code. For example, instead of doing:

MyCats a = new MyCats();
a.setAge(12);
a.setName("Foo");

You can just do:

MyCats a = new MyCats(12, "Foo");

Simpler, hum?

Other reasons you might prefer the later, if shortness is not enough:

  • You can initialize all calculated fields that depend on several fields inside the constructor, using the values provided.
  • You can validate input and thrown exceptions in case of invalid arguments, even for checks that requires multiple arguments for that.
  • You must do that if your fields are final and your class immutable, in which case there is no setters available.

Mostly in the last case, it's very useful to be able to check for correctness upon construction and disallow any objects from being in a invalid state, saving lots of errors later on.

what is the use of a parameterized constructor in java?

By the default constructor any attributes your object might have are set to 0, false et cetera. If you want to set the attributes right away you can use a parameterized constructor. Also using you own constructor of course gives you the option of executing code before the object (technically while) is created.

By the way: The answer that "the default won't set any value to the properties" is wrong. For example this code:

public class Test {
private int test;
private boolean test2;

public static void main(String[] args) {
Test test = new Test();
System.out.println(test.test);
System.out.println(test.test2);
}
}

Will print out "0" and "false".



Related Topics



Leave a reply



Submit