Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

October 30, 2015 Categories: Inheritance. No Comments on final Keyword

In this article we will look at final keyword in Java. Also we will see what is the use of final keyword in inheritance along with Java code samples.

 

Uses of final Keyword

Following are the uses of final keyword in Java:

  1. To declare constant values
  2. To make a method non-overridable
  3. To make a class non-inheritable

The second and third uses of final are applicable only in the context of inheritance. Let’s look at each of the uses of final keyword in detail.

 

Declaring constant values

The first use of final is to declare constant values in Java programs. Syntax for declaring a constant is shown below:

final data-type variable-name = value;

An example for declaring constants is given below:

final float PI = 3.1415;

In Java, you have to assign the value for the constant in the declaration time itself.

 

final for methods

The final keyword can be used to make a method in base class non-overridable. Syntax for making a method non-overridable is given below:

final return-type method-name(parameters-list)

{

//Body of the method

}

So, we can say that an abstract method cannot be declared as final.

 

final for classes

The final keyword can be used to make a class non-inheritable or non-extendable. Syntax for making a class non-inheritable is given below:

final class Class-Name

{

//Members of class

}

So, we can say that an abstract class cannot be declared as final.

Let’s consider an example to demonstrate the use of final keyword in inheritance:

The above code when compiled gives errors as the sub classes are trying to override the area() method in the super class which was declared as final.

Now, let’s look at another example:

Above code gives errors because the classes Circle and Rectangle are trying to inherit the Shape class which was declared final (non-inheritable).

 

Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up