简体   繁体   English

防止子类覆盖接口

[英]Prevent a subclass from overriding interface

Is there a way to prevent a subclass from overriding the implementation of interface that super class implement. 有没有一种方法可以防止子类覆盖超类实现的接口的实现。

I want to create a custom view contains a listView in android and implement onScroll listener but when the subclass set onScroll listener on the list. 我想在android中创建一个包含listView的自定义视图并实现onScroll侦听器,但是当子类在列表上设置onScroll侦听器时。 the listener at the super class is never invoked. 永远不会调用超类的侦听器。

Yes, there is. 就在这里。

The final word on that is: final 最终的结论是: final

By declaring a method final you state that subclasses are not allowed to @Override this method (even without annotation that is). 通过声明方法final您声明不允许子类@Override此方法(即使没有注释)。

Consider this interface: 考虑以下接口:

interface MyInter  {
   public void foo();

   public String bar();
}

And your class 还有你的课

public class MyClass implements MyInter {

  @Override 
  public final void foo() {
    //Cant touch this
  }

  @Override
  public String bar() {
    return "foo";
  }

}

Now your third class is allowed to extend MyClass - but limited to overriding bar() because foo() is protected by final keyword: 现在,您的第三个类被允许扩展MyClass-但仅限于覆盖bar()因为foo()final关键字保护:

public class Thirs extends MyClass {
   @Override
   public String bar() {
     return "bar";
   }
}

You can add final keyword to do so. 您可以添加final关键字。

Eg: 例如:

public final void foo() {
    ....
}

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

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