final
keyword is is a non-access modifier in Java.
public class FinalDemo
{
public static void main(String[] args)
{
final int MAX_MARKS = 100; // final variable (constant)
System.out.println("Maximum marks allowed: " + MAX_MARKS);
//MAX_MARKS = MAX_MARKS + 50; //error as we cannot change the final variable value
}
}
Maximum marks allowed: 100
class Parent
{
final void showMessage()
{
System.out.println("This is a final method from the Parent class.");
}
}
class Child extends Parent
{
// Trying to override the final method will cause a compile-time error
/*
void showMessage()
{
System.out.println("Trying to override.");
}
*/
}
public class FinalDemo
{
public static void main(String[] args)
{
Child obj = new Child();
obj.showMessage();
}
}
This is a final method from the Parent class.
// Final class - cannot be extended
final class A
{
void mA()
{
System.out.println("This is class A.");
}
}
// Trying to extend a final class will cause a compile-time error
/*
class B extends A
{
}
*/
public class FinalDemo
{
public static void main(String[] args)
{
A obj = new A();
obj.mA();
}
}
This is class A.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.