Constructors
by
, January 29th, 2012 at 04:52 PM (1616 Views)
We can use a constructor to quickly initialise variables as soon as our object is created. If you haven't read the above post, please do - you will become familiar with the code we're using for these examples.
Here's Class1.
class Class1{ public static void main(String args[]){ Class2 class2Object = new Class2("Tony"); class2Object.outputName(); } }
You can see what we've done here is added an argument of "Tony" to our class2Object. To use this constructor, you must make a method with the exact same name as the class in which it's in. Take a look at our Class2 code.
You will notice this new method.
public Class2(String name){ friendName = name; }
The method's name is Class2, identicle to that of our class name. Since we were able to send the name variable over to Class2 as the object was created, this now makes our setName method redundant. Its job has been taken care of.
Constructors are useful if we wanted to use multiple objects. Each object has its own set of variables. What we could do, if we wanted, would be to create another object like this.
Class2 class2Object2 = new Class2("Betty");
We could now decide to output class2Object2 or class2Object1; each would produce a different output.