简体   繁体   English

创建实例时重写方法?

[英]Override method when creating an instance?

I was looking at this example within the onCreate() method: 我在onCreate()方法中查看此示例:

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? 创建OnClickListener的实例时,对构造函数的调用还包括对onClick()方法的覆盖吗? 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. 该类将扩展OnClickListener ,因此它将继承其所有行为。 In this case, OnClickListener is an Interface, so you are creating a class that implements that interface. 在这种情况下, OnClickListener是一个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. 当您执行此操作时,只有该实例将具有该行为,因此您可以使用另一个onClick方法创建另一个实例,并且每个实例将执行不同的操作。

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. 如果是抽象类/接口,则还必须提供所有抽象方法的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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