Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it "ok" to add the final keyword to an inherited/overridden method?

In Android i create an abstract class that extends View (an Android class to which i have no access). The abstract class overrides the Views

@Override
protected final void onDraw(Canvas canvas) {
    if(conditions) return;        

    // child classes should only draw if this class gives the ok
    subDraw(canvas);
}

protected abstract void subDraw(Canvas canvas);

however i added the final keyword here.

The point is, i create an abstract method that the subclasses are supposed to use instead of the onDraw. So i prevent the onDraw from being overridden any further and it works.

I know there are designs to make this better, however this works like a charm without a lot of change. My question is more in general if doing the above has unwanted side effects at runtime or other issues ?!

like image 562
NikkyD Avatar asked Oct 27 '16 12:10

NikkyD


People also ask

What happens if we try to override a final method?

Can We Override a Final Method? No, the Methods that are declared as final cannot be Overridden or hidden. For this very reason, a method must be declared as final only when we're sure that it is complete.

What happens if a method has the final keyword as modifier?

When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final.

Can you override inherited methods?

To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. Any method that is called must be defined within its own class or its superclass.

Can we override already overridden method?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.


1 Answers

Yes, technically it's a clean solution. If you are absolutely sure there is no situation when someone might want to change any logic inside this particular method you could do that.

Also, you have to remember that this method has to contain the least logic possible, as it can not be altered by any descendant. If you think this method will grow in size (without using delegates) avoid finalizing it.

like image 131
Boris Schegolev Avatar answered Oct 29 '22 22:10

Boris Schegolev