user6840743
user6840743

Reputation:

Java Android - new class function defined inside method?

Hello i have recently started programming in java especially on android, since im new to java , i found something that i dont understand.

theListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String pickedLanguage = "Your favorite programming language is : " + String.valueOf(parent.getItemAtPosition(position));
                Toast.makeText(MainActivity.this,pickedLanguage,Toast.LENGTH_LONG).show();
            }
        });

What i dont understand:

Upvotes: 0

Views: 52

Answers (1)

Jans
Jans

Reputation: 11250

It's called anonymous classes and are commonly used to give interface implementation to a method when its called, without creating a separate class that implement the interface for later instantiate it.

In this case the method setOnItemClickListener receive an instance of interface OnItemClickListener, we can create a separate class that implement that interface and to later instantiate or just provide to the method an anonymous implementation at the moment of calling.

You can find more detail Anonymous Classes

Upvotes: 3

Related Questions