Prevent runtime method overrides in Java

>Class a method X ()

I want to create a class lib that will extend the activity class and override the methods (and more) that handle the back button in Android I want the developer to extend my class and continue to use his active class like me, but force him to call the superclass of the method

Know how class B prevents its X methods from being overridden at run time?

(I don't want to complete X in level B)

to update:

OK, let me try to explain what I want to achieve - I want to create a class lib that will extend the activity class and override the methods (and more) that handle the back button in Android I want the developer to extend my class and continue to use his active class like me, but force him to call the superclass of the method If he doesn't, I'll be in trouble

Solution

One solution is to make your method final, but let it call the second method you declare abstract Then let other developers write the implementation of the abstract method

For example, your code might look like this:

public final void method() {
    // do your stuff
    // ...

    // call the method that the other developer wrote
    doMethod();
}

protected abstract void doMethod();

Whoever adds functionality that must be called at the end of a method must implement an abstract method to extend your class and compile its code:

protected void doMethod() {
    // do more stuff
}

Then you will continue to call method () as you are now (but remember, this does not prevent others from calling domethod () directly, so you still need to clearly record the API.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>