View Single Post
  #3 (permalink)  
Old September 2nd, 2011, 10:26 AM
John Moore John Moore is offline
Registered User
Points: 9, Level: 1
Points: 9, Level: 1 Points: 9, Level: 1 Points: 9, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2011
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Smile Possible Explanation of How the P.37 Code Works!

I also found out after researching the AlertDialog.Builder class that the methods of the class return a reference to the same instance of the AlertDialog.Builder class. So in effect, you've got a chain of method calls, each using the returned reference.

I wrote the following test to demonstrate how this works:
Code:
public class C1 {
	public C1(){
		System.out.println("C1 Constructor Called");
	}
	
	public C1 M1(){
		System.out.println("M1 Method Called");
		return(this);
	}
	
	public C1 M2(){
		System.out.println("M2 Method Called");
		return(this);
	}
	
	public C1 M3(){
		System.out.println("M3 Method Called");
		return(this);
	}
	
	public C1 create(){
		return(this);
	}
}



public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		C1 cONE = doTest();
		System.out.println("Call method M3 via returned reference!");
		cONE.M3();
	}
	
	static public C1 doTest(){
		int choice = 0;
		
		switch(choice){
		case 0:
			return new C1() 
				.M1()
				.M2()
				.M3()
				.create();
		}
		return null;
	}
	
}
Each method of the C1 class returns this - which is the key to being able to chain the methods in the switch statement above. The conventional way to write the switch statement would have been as follows:
Code:
switch(choice){
   case 0:
	C1 cOne = new C1(); 
	cOne.M1();
	cOne.M2();
	cOne.M3();
	cOne.create();
	return cOne;
}
Whether the new way is more efficient than the conventional way is the question? Anyone have an opinion?
Reply With Quote