this - a compelling example - top of Musings page

By: Nicholas Duchon


// File: MyThisExample.java
// Date: Dec 6, 2006
// Author: Nicholas Duchon

// A use of the keywork "this" that I find compelling
// The calls could be done with a 3-parameter setter
// But this way, the order is still open,
// and not all calls need to be made at once, or at all, for b.

// The call-chaining here is not legal when using class MyA
// since the methods there return void. Check this out yourself!

public class MyThisExample {
public static void main (String args []) {
MyA a = new MyA ();
MyB b = new MyB ();
System.out.println ("a - before: " + a);
System.out.println ("b - before: " + b);

a.setFirst ("Nicholas");
a.setLast ("Duchon");
a.setGrade (95.37);

b.setFirst ("James").setLast("Carter").setGrade(96.34);

System.out.println ("a - after: " + a);
System.out.println ("b - after: " + b);

// The following is illegal since these methods return void
// a.setFirst ("Karen").setLast("Shelly").setGrade(96.34);

} // end main
} // end class MyThisExample

class MyA {
String first, last;
double grade;

public void setFirst (String s) {
first = s;
} // end setFirst

public void setLast (String s) {
last = s;
} // end setLast

public void setGrade (double s) {
grade = s;
} // end setGrade

public String toString () {
return first + " " + last + " grade: " + grade;
} // end toString
} // end class MyA

class MyB {
String first, last;
double grade;

public MyB setFirst (String s) {
first = s;
return this;
} // end setFirst

public MyB setLast (String s) {
last = s;
return this;
} // end setLast

public MyB setGrade (double s) {
grade = s;
return this;
} // end setGrade

public String toString () {
return first + " " + last + " grade: " + grade;
} // end toString
} // end class MyB

ND.