OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 8 : Final Class and Methods in Java
Unit - 2
Topic - 8 : Final Class and Methods in Java
The final
keyword in Java can be applied to classes, methods, and variables.
In this section, we will focus on its use with classes and methods.
1. Final Class
A final class is a class that cannot be inherited.
Once a class is declared as final
, no other class can extend it.
Uses of Final Class
-
Prevent Inheritance
-
Example: All wrapper classes in Java (
Integer
,Float
,Double
, etc.) are final.
-
-
Create Immutable Classes
-
Example: The predefined
String
class isfinal
, ensuring that its state cannot be changed after creation.
-
Example: Final Class
Output:
2. Final Method
A final method is a method that cannot be overridden in subclasses.
If you declare a method as final
, all derived classes must use the same implementation.
Example: Final Method
Output:
Key Points
-
A final class cannot be extended.
-
A final method cannot be overridden.
-
The
final
keyword is often used to:-
Ensure security and prevent unwanted changes.
-
Maintain consistent method behavior across subclasses.
-
Create immutable classes.
-
Comments
Post a Comment