Friday, August 11, 2017

Final keyword


It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance.

final keyword can be used in following way.

  1. Final at variable level
  2. Final at method level
  3. Final at class level



Final at variable level

Final keyword is used to make a variable as a constant.

A variable declared with the final keyword cannot be modified by the program after initialization.


Example

public class Circle

{

public static final double PI=3.14159;

public static void main(String[] args)

{

System.out.println(PI);

}
}



Final at method level

It makes a method final, meaning that sub classes cannot override this method.


Example

class Employee

{

 final void disp()

{ System.out.println("Hello Good Morning");

 }
}

class Developer extends Employee

{

void disp()

{

System.out.println("How are you ?");

} }

class FinalDemo

 {

 public static void main(String args[])

{

Developer obj=new Developer();

obj.disp();

}
}


Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes.

example

final class Employee

 {

 int  salary=10000;

 }

class Developer extends Employee

{ void show()

 {

 System.out.println("Hello Good Morning");

} }

 class FinalDemo

{

 public static void main(String args[])

 {

Developer obj=new Developer();

 obj.show();

}
}

No comments:

Post a Comment