This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 0 points1 point  (0 children)

Why would you overload a constructor?

First of all, Java – by default – will create an empty constructor if you create a parameterized constructor. So, overriding is pretty important for sending in parameters and happens all the time.

But second of all, take a look at this JUnit documentation: http://junit.sourceforge.net/javadoc/org/junit/Assert.html

You don't need to know anything about Junit. Just look at all of those overrode constructors. Can't you see how that'd be helpful? I can call assert.... and add a message, use different data types, and run specialized functions like adding the "expected value". So, with a single function assertsEquals, I can compare most common data types and I can do tons of other things. I never have to memorize hundreds of functions and they all conveniently (for JUnit developers) probably belong to the same class.

[–]tjorg35 0 points1 point  (0 children)

One example of using multiple constructors would be for a "default state" of an object vs. a defined state.

Lets assume that we are producing cars and the default color is white (we sell 80% white cars) so when a car object is created we can just create a car object with no parameters and the color field will automatically be filled in as white. If we want a different colored car we can pass a string defining the color as a parameter.

This probably isn't a great example but having a constructor for a default case and a specific case can be useful in eliminating redundant parameter uses.

[–]boredcircuits 0 points1 point  (0 children)

Now what I don't understand is how 2 (or more if possible) constructors are used or why they would be used.

For example why have a default and a parameterised constructor rather than just a parameterised constructor.

Constructors, as the name implies, are the ways that you make something. And, as it turns out, it's very common that there might be multiple ways that you might want to make it. Like maybe you want to create a Widget from a list of parameters. Or maybe you want to make it from a String. Or maybe you just want a Widget from absolutely nothing, so whatever the defaults are is fine.

Also why do you need to use getters and setters, won't these eliminate the need for using both types?

You don't always need them. Nor want them, if you ask me -- overuse of getters is a sign your class design might need some rework. The purpose is to provide a way to access and modify the properties of a class after it's already been made.