.


Divya

Java final Keyword


It is used in 3 phases in java:

  1. variable
  2. method
  3. class

Java final variable

Its value cant be changed during the scope of the program

Syntax of Super final variable

final StringBuffer a;

Example

class Student
{
public static void main(String[] args)
{
final StringBuilder a = new StringBuilder("reading");
System.out.println(a);
b.append("playing");
System.out.println(b);
}
}

Output :
reading
playing

Java final method

It cant be overridden.

Syntax of Super final method

class A
{
final void method1()
{
System.out.println("True.");
}
}
class B extends A
{
void method1()
{
System.out.println("False");
}
}

Example

class Fruit{
final void run(){System.out.println("eating");}
}
class Apple extends Fruit{
void run(){System.out.println("it is very costly");}
public static void main(String args[]){
Apple a= new Apple();
a.run();
}
}

Output:Compile Time Error

Java final class

It cant be inherited.

Syntax of Super final class

final class A
{
}
class B extends A
{
}

Example

final class Fruit{}
class Apple extends Fruit{
void run(){System.out.println("It is very costly");}
public static void main(String args[]){
Apple a= new Apple();
a.run();
}
}

Output:Compile Time Error



.