Рет қаралды 52
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that has no value it is called blank final variable or uninitialized final variable.
It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in the static block only.
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}
Output:- Compile time error
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
} // compile time error
java final class
If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph"); }
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
} // compile time error
initialization of final variables
There are three ways to initialize a final variable :
you can initialize a final variable when it is declared.
A blank final variable (not initialized) can be initialized inside instance-initializer block or inside constructor.
A blank final static variable can be initialized inside static block.
class Test
{
final int THRESHOLD = 5;
final int CAPACITY;
final int MINIMUM;
static final double PI = 3.14;
static final double EC;
{
CAPACITY = 25;
}
static{
EC = 2.3;
}
public Test()
{
MINIMUM = -1;
}
}
local final variables
If local variable is final then you need to initialize the final variable in the declaration itself.
void funName( )
{
final int MAX=100; // initialization here
}
finalize method
It is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection
Once the finalize method completes immediately Garbage Collector destroy that object.
finalize method is present in Object class and its syntax is:
protected void finalize throws Throwable{ }
class Hello {
public static void main(String[] args)
{
Hello obj = new Hello();
obj =null;
// Requesting JVM to call Garbage Collector method
System.gc();
System.out.println("Main Completes");
}
public void finalize()
{
System.out.println("finalize method overriden");
}
}