Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exact way how final methods works in java

Tags:

java

final

class Clidder {
    private final void flipper() {
        System.out.println("Clidder");
    }
}
public class Clidlet extends Clidder {
    public final void flipper() {
        System.out.println("Clidlet");
    }
    public static void main(String args[]) {
        new Clidlet().flipper();
    }
}

what is the result? to this question I expected the answer "compilation fails" because final method cannot be overridden and it does not allow inheritance. but the answer was "Cliddet" why is that? did I misunderstand something in this concept. how can this be the output? please explain.

like image 703
vidya Avatar asked Jun 17 '16 03:06

vidya


People also ask

What does final method do in Java?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .

What is final and how it has been used variables and methods?

What is the Final Keyword in Java? Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses.

What are the 3 uses of final keyword in Java?

Create Constants, prevent inheritance, and prevent methods from being inheritance are the three main uses of final keyword in java.

What happen when we declare method as final?

We can declare a method as final, once you declare a method final it cannot be overridden. So, you cannot modify a final method from a sub class. The main intention of making a method final would be that the content of the method should not be changed by any outsider.


1 Answers

The private modifier indicates that the method of flipper() in class of Clidder can not be seen from child class Clidlet. So it is not overriding but just looks like a new method declaration in the child class. Private method/field can not be override because it can not be seen.

like image 134
LynxZh Avatar answered Oct 13 '22 18:10

LynxZh