Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: John Cooper   on Feb 28 In Java Category.

  
Question Answered By: Hadil Khan   on Feb 28

> First question, can a java code  have two "constructors"?

Yes ... A class  can have as many constructors  as it needs.

The most used example of multiple constructors is a constructor  with no
arguments and a constructor with arguments.

Constructors with no arguments are there so you can simply call that
Object and then fill all the data you self ie:

Object o = new Object();
o.someMethod(someData);

While Constructors that accept arguments fill in some level of data ie.

Object o = new Object(someData);

> And why it needs "constructors" to set  the values?

It doesn't need a constructor to set the values, it could force the
programmer to construct all the information.

Lets assume that you had another constructor that was like this

Die () {
}

This is called a nullery constructor (because it does nothing).

To call this object you code

Die d = new Die();

Now this method doesn't set any values. To set those values you would
have to do this;

d.numFaces = 6;
d.faceValue = 1;

> What do constructors usually do anyway??


Constructors are basicly the first thing that is called when you
"construct" a object.

In your case when you make a Die Object you have two ways of making it.
One that has 6 sides and one that can have more than 4 sides.

In this case you can use the constructors to be a default and a
non-default mode.

Die d = new Die(); <- creates a standard 6 sided die
Die d = new Die(255); <- creates a 255 sided die.

Share: