Google+

Like Us On Facebook


Total Pageviews

113. Prevent overriding using 'final' keyword






The keyword final has three uses:

1. To create an equivalent of a named constant explained in post# 91 final instance variable
2. The other two uses of final apply to inheritance

The first use of 'final' in inheritance is to 'Prevent overriding'. Methods declared as final in the superclass cannot be overridden by the subclass.

Lets implement this on Eclipse IDE:

1.Create superclass 'Superclass' containing a method specified as 'final' as shown below and save:



2. Create subclass 'Subclass' , to override the method specified as 'final' in superclass as shown below and save:



3. Observe that an error "Cannot override the final method from superclass" is displayed as shown below:



After looking at the error, its very clear that the methods specified as 'final' in superclass can't be overridden by the subclass.

So we've to specify the methods in superclass as 'final', if and only if we don't want the sub classes to override the methods.

Download this project:

Click here to download the project containing the 'Superclass' and 'Subclass' files used in this post (You can download the project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

Prevent inheritance using 'final' keyword  will be explained in the next post.



No comments:

Blog Index