Java Unnamed Objects

I've been learning coding for 2 months. I'm working in Java on the Android platform. I'm trying to understand unnamed objects better.

In reference to the 7th line of this example, "this.button2.setOnClickListener(new OnClickListener(){...});"

a) Is the OnClickListener an object? (I think it is, since the "new" keyword was used)

b) Can (and should) it be named?

c) How would it be named?

d) How would one refer to it in the future? Is it possible? Can it be modified during runtime, if needs be?

e) Would this work?: "this.button2.setOnClickListener(OnClickListener namedObject = new OnClickListener(){//methods go here});"

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main2);     
    this.button2 = (Button) this.findViewById(R.id.button2);    
    this.button2.setOnClickListener(new OnClickListener()   
    {
        public void onClick(View v) 
        {                       
            Intent i = new Intent(getApplicationContext(), Absolute.class);
            startActivity(i);
        }
    });
}

Answers


a) Yes, it is an object.

b) Yes, it can be named, but it does not necessarily need to be (if you won't need to refer to it in the future, or have some other way of referring to it).

c) You can do:

OnClickListener myOnClickListener = new OnClickListener() {
    // Contents of the OnClickListener go here...
}
this.button2.setOnClickListener(myOnClickListener);

d) If you had named it (as seen above), it can be referred to by the name. It can be referenced at runtime if you have a reference to it by invoking any mutator methods on the object.

e) That syntax is not valid. See (c) for the proper way to make this call.


Need Your Help

Finding out related data from tables

php mysql codeigniter

I have three tables in my mysql database which looks like following:

Use onTouchEvent in AlertDialog

android android-activity alertdialog android-softkeyboard ontouchevent

In the activity state, I can use the following code to hide Soft Keyboard on the device at EditText (mEtEmailUser) automatically by touching on the screen of the device: