|
Overloading Constructors. |
|
|
|
Today we are going to Overload the Computer. No... wait... thats... Overload the constructor of a Computer. Ok... I think I got it this time... were Overloading the constructor of a Class “called” Computer. Ah yes... thats better.
Here we have a very simple class called Computer
public class Computer { String name; // Brand name int speed; // Processor int diskspace; int monitor; // size boolean floppy; boolean dvd;
Now by default we get a no parameter constructor for free. And with a default no parameter constructor we could instantiate (build) an instance of the Computer Class in memory but it would have no value. Oops, I meant no values set its member variables. In effect we have an empty shell of a Computer. So instead this Class has a parameterized constructor.
Computer(String n, int s, int d, int m, boolean f, boolean v) { name = n; speed = s; diskspace = d; monitor = m; floppy = f; dvd = v; }
This constructor will require that we set every member variable with a value. A problem has popped up out on the sales floor in that all of the sales people have voted. They all agree that it is a pain to have to indicate if the customer wants a DVD or Floppy drive. They tell us that nobody wants a Floppy drive anymore and everyone wants a DVD. Well, the line is drawn in the sand and we lost. We now have to alter our Computer Class so that the sales person can skip entering values in the DVD and Floppy fields on the order form. Now I know it might be hard to believe... but it is possible that some misguided soul will want a computer without a DVD and with a Floppy drive. Therefore, we will leave the original constructor as it is and write another constructor into the class. This constructor will have the same name as the other one but will require a different set of parameters.
Computer(String n, int s, int d, int m) { name = n; speed = s; diskspace = d; monitor = m; floppy = false; dvd = true; } Notice we are not requiring that values be passed in for the Floppy or DVD but instead we are setting them do a “default” value to keep the sales staff happy. So now we have two constructors. When a constructor is called the “JVM” will choose which one to use based on the parameter list being passed with the call.
This brings up the point that the parameter list must match exactly. Both the type of data and the order of the data as defined in the parameter list of the constructor make up what is referred to as the signature of the constructor. By changing the types and or the order of the parameters we can make unique signatures thereby allowing more than one constructor with the same name to exist with it causing a conflict or failure.
So to Overload a constructor... is to use the same name for the constructor but have a different signature (parameter list).
Next time we will cover overloading methods.
|