Overriding is a one of the mechanisms to achieve polymorphism. This is the case when we have two classes where, one inherits the properties of another using the extends keyword and, these two classes same method including parameters and return type (say, sample).
Since it is inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass.
When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.
No, you cannot override final method in java. If you try to do so, it generates a compile time error saying
class Super{ public final void demo() { System.out.println("This is the method of the superclass"); } } class Sub extends Super{ public final void demo() { System.out.println("This is the method of the subclass"); } }
Sub.java:7: error: demo() in Sub cannot override demo() in Super public final void demo() { ^ overridden method is final 1 error
If you try to compile the same program in eclipse you will get the following error −