ARTICLE AD BOX
In class, our teacher showed us this:
The third is a way to call alternate constructors from within a constructor. Use this to call alternate constructors. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo { public Foo() { this("Some default value for bar"); // Additional code here will be executed // after the other constructor is done. } public Foo(String bar) { // Do something with bar } // ... }However, we didn't get a chance to talk about why one would do this before class ended. I am trying to prepare for Friday lecture, but am not sure I see the need for implementing constructors this way. I suppose that constructor Foo() is doing something different than the parameterized constructor based on the comments he gave above in the code, but I don't see the need for it, practically speaking. Does anyone have some real-world examples of the need to do things this way?
I ask because whenever I implement the program this way:
public class Pay { private double pay; public Pay(double p) { pay = p; } public double getPay() { return pay; } public void calculatePayWithOvertime(Pay x) { Overtime ot = new Overtime(x); pay = ot.getOvertimePay(); } public static void main(String[] args) { Pay myPay = new Pay(100.0); myPay.calculatePayWithOvertime(MyPay);// alternate implementation System.out.println(myPay.getPay()); } } class Overtime { private double payWithOvertime; public Overtime(Pay p) { payWithOvertime = p.getPay() * 1.5; } public double getOvertimePay() { return payWithOvertime; } }the program still runs correctly as far as I can tell. I don't really like typing up
myPay.calculatePayWithOvertime(myPay);
that seems like poor style more than anything else...is that also a reason?
