0% found this document useful (0 votes)
5 views3 pages

Understanding Java's Final Keyword

The final keyword in Java is used to restrict modifications to variables, methods, and classes. A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended. Examples provided illustrate the usage and errors encountered when attempting to modify final elements.

Uploaded by

ou638009
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Understanding Java's Final Keyword

The final keyword in Java is used to restrict modifications to variables, methods, and classes. A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended. Examples provided illustrate the usage and errors encountered when attempting to modify final elements.

Uploaded by

ou638009
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Final Keyword In Java:

The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
 variable
 method
 class

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Syntax: final datatype variable_name = value;


Example : final double pi = 3.142;

Program:

class FinalVariable {
public static void main(String[] args) {
final double pi = 3.142;
[Link]("pi value is :"+pi);
pi =5.43;
[Link]("pi value is :"+pi);
}
}
error:
[Link]: error: cannot assign a value to final variable pi
pi =5.43;

2) Java final method


If you make any method as final, you cannot override it.

Syntax: final returntype methodName(parameters list)


Example: final void display()

Program:
class A
{
final void display()
{
[Link]("This is display() method in A class ");
}
}
class B extends A
{
void display()
{
[Link]("This is display() method in A class ");
}
}
class FinalMethod
{
public static void main(String[] args)
{
B obj = new B();
[Link]();
}
}
error: display() in B cannot override display() in A
void display()
^
overridden method is final

3) Java final class

If you make any class as final, you cannot extend it.

Syntax: final class ClassName


Example: final class Demo

Program

final class A
{

void display()
{
[Link]("This is display() method in A class ");
}
}
class B extends A
{

void display()
{
[Link]("This is display() method in A class ");
}
}
class FinalClass
{
public static void main(String[] args)
{
B obj = new B();
[Link]();
}
}

error: cannot inherit from final A


class B extends A

You might also like