Java syntax help

Put your problem here if it does not fit any of the other categories.

Java syntax help

Postby spentakapps » Fri Jan 14, 2011 12:43 am

I'm an avid C# programmer, but Java is new to me. Its all pretty similar, but I can't quite make out what this is:
Code: Select all
private void openNewGameDialog()
    {
      new AlertDialog.Builder(this)
      .setTitle(R.string.new_game_title)
      .setItems(R.array.difficulty, new DialogInterface.OnClickListener()
      {
         public void onClick(DialogInterface dialog, int which)
         {
            // TODO Auto-generated method stub
            
         }
      })
      .show();
   }


In C# i would instatiate a new object by doing this AlertDialog myAlert = new AlertDialog; But in this code i'm not really sure what is happening. new AlertDialog.Builder(this).setTitle(R.string.new_game_title).setItems...

Are we calling methods? Are we creating an object? What is this doing?
spentakapps
Freshman
Freshman
 
Posts: 8
Joined: Sat Jan 08, 2011 3:41 am

Top

Re: Java syntax help

Postby Skiller » Fri Jan 14, 2011 2:22 am

Yer, I've come from C++ so I've been thrown by java quite a bit here and there too.

Anyway what it's doing is creating a new, what I believe is called, anonymous class, that overrides the onClick method of the DialogInterface.OnClickListener class, it's pretty cool because things that would normally need to have many variations of a simple class (like onClickListener) can just be done like this without needing to create and name each specific class :).

However from what I gather you need to be careful with this stuff as if it accesses any data from the class that created it, the anonymous class will implicitly create a reference to it which can cause problems for the garbage collector is some circumstances.
Skiller
Developer
Developer
 
Posts: 33
Joined: Sun Nov 28, 2010 8:35 pm
Location: Australia

Re: Java syntax help

Postby spentakapps » Fri Jan 14, 2011 5:24 am

Thanks for the help on this. Your post led me to anonymous class tutorials. The code I posted not only instantiates an anonymous class, but then has a method that instansiates an anonymous interface which defines an override method (onClick) in its interface body. Whew!
spentakapps
Freshman
Freshman
 
Posts: 8
Joined: Sat Jan 08, 2011 3:41 am

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 15 guests