简体   繁体   中英

Override method when creating an instance?

I was looking at this example within the onCreate() method:

protected void onCreate(Bundle savedInstanceState) {

    Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo); 
    launchActivityTwoButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent activityTwoIntent = new Intent(v.getContext(), ActivityTwo.class);
            startActivity(activityTwoIntent);

        }
    });
}

When an instance of OnClickListener is created, the call to the constructor also includes an override to the onClick() method? Is there a correct term for what this is? Also, when you override the method when creating the instance, does the method override only apply for that specific instance?

What you are doing there is creating an annonymous class . That class will extend OnClickListener , so it will inherit all of its behaviour. In this case, OnClickListener is an Interface, so you are creating a class that implements that interface.

When you do that, only that instance will have that behaviour, so you can create another one with another onClick method, and each of them will do different things.

You can read more about Annonymous classes here

The correct term you are searching for is "anonymous class" - you create a class "on the fly" without naming it and persisting it in a file. In case of abstract classes/interfaces, you have to provide an implementation of all abstract methods as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM