“final”- KEYWORD

“final” is a keyword in java which provides code restricted.

final can be used with variables, methods and classes.

It cannot be used for blocks and constructors.

 the "final” keyword in a method declaration to indicate that the method cannot be overridden by subclasses.

NOTE: We can also declare an entire class final. A class that is declared final cannot be subclassed.

1. “final” keyword in variables:

We cannot change the value of a final variable once it is initialized.

EXAMPLE:

int a=5; // constant
int b=6; // variable
.
.
.
a=15; // compiler throws error

The above example shows that we can’t change the value ie) won’t work for ‘a’. We cannot reassign the value.

2. “final” keyword in methods:

final method can’t be overridden. It will definitely gets inherited.

EXAMPLE:

class A
{
int n()
{
}
final int m()
{
}
class B extends A
{
int m() // we can get properties from final keyword method but we can’t modify it.
{
}
}

3.”final” keyword in class:

We cannot extend a final class. A class that is declared final cannot be subclassed.

EXAMPLE:

final class A
{
//string class in java
}

Leave a comment

Design a site like this with WordPress.com
Get started