Skip to main content

Practical-25

Write a Java Program to implement final class and final method.

Introdution

A final class is an unchangeable class whose structure can not be changed. It has exactly the same properties as any non-final class. Any class that is defined as final cannot be extended, i.e. it cannot be used to create a new class with its properties modified or improved. A final method cannot be overridden, i.e. it cannot be changed. Final methods are used to avoid accidental modifications or to ensure that certain methods remain static or cannot be painted.

Code

// Java code for final class
final class FinalClass {

final int x = 10;

// final method
final void display()
{
System.out.println("Hi");
}
}

// classs cannot extend final class:
public class SubClass extends FinalClass {

// cannot override final method
public void display()
{
System.out.println("Hello");
}

public static void main(String[] args)
{
SubClass obj = new SubClass();
obj.display();
}
}

Output

Hi
Explanation

The above program implements a final class that contains a final method, both of which cannot be changed or overridden. The class SubClass is attempting to override the final method, but it is being prevented from doing so.