Saturday, June 27, 2009

constructor tricks: constructor overloading, calling constructor from constructor


Did I catch your attention with the megan fox picture?
I assume that the answer is yes, great.

Constructor overloading is not really different from a method overloading.
In practice, all you have to do is to give different arguments to similar methods.
For a Fruit class,
  Fruit(String name_, int count_) 
and
  Fruit(String name_, int count_, String color_) 
are both constructors. They are similar in almost every way; only difference is that the second one has a color attribute.

Now, let's move to a more tricky subject. Calling a constructor from another constructor. You can ask why would I want to do that. Let's see it on our example:

 public class Fruit {

int count;
String name, color;
final static String SEPARATOR = ", ";
// the part below is where I use constructor overloading
Fruit(String name_, int count_){
name = name_;
count = count_;
}

Fruit(String name_, int count_, String color_){
name = name_;
count = count_;
color = color_;
}
// the part above is where I use constructor overloading

public String toString(){
String returnValue = "name: "+name+SEPARATOR+"count: "+count;
if(color != null)
returnValue += SEPARATOR+"color: "+color;

return returnValue;
}

public static void main(String[] args) {
// create three apples which I dont care the color
Fruit apples = new Fruit("apple", 3);
System.out.println(apples);

// create two yellow melons
Fruit melons = new Fruit("melon", 2, "yellow");
System.out.println(melons);
}

}


As you can see the example is pretty straightforward. This is the fruit class. There are two mandatory and one optional attribute related to my class. Fruit name and fruit count are mandatory and the color is optional. So to have this effect, I used constructor overloading.

Now lets see why would I want to call a constructor from another constructor. As you can see both constructors in the example share the mandatory attributes. So I can easily call the first constructor from the second one (by using this() keyword) and remove the code that has a reoccurence. The below code is improved in readability as you can see.

 public class Fruit {

int count;
String name, color;
final static String SEPARATOR = ", ";

Fruit(String name_, int count_){
name = name_;
count = count_;
}
/*
removed two redundant lines and added "this" to call the constructor above.
we give its essential parameters (name and count) by passing them
to "this" as arguments.
*/

Fruit(String name_, int count_, String color_){
this(name_, count_);
color = color_;
}

public String toString(){
String returnValue = "name: "+name+SEPARATOR+"count: "+count;
if(color != null)
returnValue += SEPARATOR+"color: "+color;

return returnValue;
}

public static void main(String[] args) {
Fruit apple = new Fruit("apple", 3);
System.out.println(apple);

Fruit melon = new Fruit("melon", 2, "yellow");
System.out.println(melon);
}

}

No comments:

Post a Comment