Search code examples
classoopprivatefinal

why use final as modifier when we have private in method classes


Let's consider that we have a method which has been declared as below:

final private method myMethod() {

}

Why should we use final when we have private as a modifier. What exactly is the purpose of final here?


Solution

  • final prevents a method from being overriding in any subclass. But it is still accessible from other classes.

    private makes a method inaccessible from any other class.

    So make a method final when you want to make sure that no child class overrides(changes the implementation) this method.

    Make it private when you want that no other class should be able to use it directly.