Final
Final
final Keyword-Definition
In Java, Final keyword is used as a constant type keyword. Used to create a variable, method, and a class as constant. Can be used with respect to:
Variable Method Class
final Variable
Is used to make a variable constant. Once a variable is made constant, its value cannot be changed, so a default value is supplied to it initially. Syntax:
final [static/private/protected] <type> <varname> [=Value]; Example: final int x; //initialised with 0 final int y=300;
final Method
Cannot be overridden in any sub class. One method has to be used throughout the inheritance. Syntax:
final <return type> <method name([argument list])> Example: final void add()
Example
class Add { private float x,y; Add() { x=10; y=20; } Add(float a, float b) { x=a; y=b; } final void addition() {
System.out.println(Additio n of Floats: +(x+y)); } } class Plus extends Add { private String x,y; Plus() { x= New; y=Delhi; } Plus(String a, String b) { x=a; y=b; } void addition() { super.addition(); System.out.println(Addition of Strings: +(x+y)); } }
An error will be produced because method addition() is defined as final in class Add, so it cannot be overridden. To remove the error, we can rename the addition() method in sub class.
Example- revised
class Add { private float x,y; Add() { x=10; y=20; } Add(float a, float b) { x=a; y=b; } final void addition() { System.out.println(Addition of Floats: +(x+y)); } } class Plus extends Add { private String x,y; Plus() { x= New; y=Delhi; } Plus(String a, String b) { x=a; y=b; } void adding() { super.addition(); System.out.println(Addition of Strings: +(x+y)); } }
class OvrMain
{
public static void main(String arg[]) { Add ob1= new Add(10, 20); ob1.addition();
final Class
Cannot be extended in other classes. Can only be used by its objects. Properties of a final class are not inheritable. Works as a stand-alone class. Syntax: final class <class name> Example:
Example-final class
final class DemoFinal { private int x=5, y=7; DemoFinal() { x=10; y=20; } class MainClass { public static void main(String arg[])
{
DemoFinal ob= new DemoFinal(); ob.show(); DemoFinal ob1= new DemoFinal(20, 30);
DemoFinal(int a, int b)
{ x=a; y=b; } } }
ob1.show();
void show()
{ System.out.println(X=+x+Y=+y); } }