Final method in java can be extended but alongside the main concept to be taken into consideration is that extend means that you can extend that particular class or not which is having final method, but you can not override that final method. One more case where you can not extend that final method is the class that contains the final method is also a final class.
Approaches:
Here we will be discussing out two approaches in order to satisfy what we just stated above to figure out how the final method is extended.
- Without over-riding
- With over-riding
Implementation:
- ‘GFGParent’ class is having a final method randomly named it ‘dataDisplay()’ which is created as the final method here.
- ‘GFG’ class extends GFGParent but the program executes without any error hence we can extend a final method but can not override it.
- Here if you had made the GFGParent class as final as also you will not extend the final method as we can not inherit the final classes.
Example 1
Java
import java.io.*;
class GFG extends GFGParent {
public static void main (String[] args) {
System.out.println( "GFG!" );
GFGParent gfg = new GFGParent();
gfg.dataDisplay();
}
}
class GFGParent {
public final void dataDisplay () {
System.out.println( "Data Structure" );
}
}
|
OutputGFG!
Data Structure
Example 2
The only change that we will be making here is we are simply trying to override the method inside child class.
Java
import java.io.*;
class GFGParent {
public final void dataDisplay()
{
System.out.println( "Data Structure" );
}
}
class GFG extends GFGParent {
public final void dataDisplay()
{
System.out.println( "Data Structure 2" );
}
public static void main(String[] args)
{
System.out.println( "GFG!" );
GFGParent gfg = new GFGParent();
gfg.dataDisplay();
}
}
|
Output: It generates a compile-time error.
