Explain about Final and Abstract Keywords in Java?

https://www.computersprofessor.com/2016/12/explain-about-final-and-abstract.html
Final is a keyword to
prevent overridden.
Final is used at 3
levels.
1. Final at variable
level
2. Final at class
level
3. Final at
method level
Final variables and Methods: |
|
All methods, variables
& classes can be override by default in subclasses.
|
|
If we wish to prevent the
subclasses from overriding the members of the superclass, we can declare them
as final using the keyword final as a modifier.
Ex
: final
int s = 10 ;
final void show ( )
{
=
}
making a method final ensures that the functionality defined in this method will never be altered in any way. similarly, the value of a final variable can never be changed. Final variables, behave like class variables and they do not take any space on individual objects of the class.
Final Classes :
|
|
Some times we may like to prevent a class being further subclassed for security reasons. a class that can not be subclassed is called a final class.
|
|
This is achieved in java
using the keyword final .
final class SS
{
=
}
|
|
Any attempt to inherit the
classes will cause an error is compiler will not allow it. Declaring a class final prevents any unwanted extensions to the class.
|
|
Abstract Methods and Classes:
|
|
Making a method final
means that method is not redefined in a subclass i.e., that method can never
be subclassed.
|
|
Java allows us to do something
that is exactly opposite to this that is we can indicate that a method must
always be redefined in a subclass. Thus making overriding compulsory.
|
|
This is done using
abstract keyword.
abstract class shape
{
…….
…….
…….
abstract void draw ( ) ;
……
……
……
}
|
|
Abstract methods are
unimplemented methods (Or) no body methods (or) declare methods.
|
|
When one method is
abstract then declare the class as abstract class.
|
|
If the class is abstract
class don’t instantiate that class because no use.
|
|
Abstract class contain
abstract methods (or) concrete methods (or) both.
|
|
If method is abstract
then the class is abstract.
|
|
If class is abstract then
the method may not be abstract.
While using abstract classes, we must satisfy the following conditions: 1. We can not use abstract classes to instantiate objects directly 2. The abstract methods of an abstract class must be defined in its subclass. 3. We can not declare abstract constructors or abstract static methods. |
|