freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Final keyword

1.Final is the modifier applicable for classes, methods and variables (for all instance, Static and local variables).
2.if a class is declared as final, then we cannot inherit that class i.e., we cannot create any child class for that final class.
3.Every method present inside a final class is always final by default but every variable present inside the final class need not be final.
4.The main advantage of final modifier is we can achieve security as no one can be allowed to change our implementation.
5. But the main disadvantage of final keyword is we are missing key benefits of Oops like inheritance and polymorphism. Hence is there is no specific requirement never recommended to use final modifier.

Java Images

method overriding

class Parent
{
void andhra()
{
System.out.println("hi");
}
}
class Child extends Parent
{
void andhra()
{
System.out.println("hello");
}
public static void main(String[] args)
{
Child c=new Child();
c.andhra();
}
};

intput and output

output:hello

overrding the method is not possible

class Parent
{
void abc()
{
System.out.println("hello");
}
}
class Child extends Parent
{
final void abc()
{
System.out.println("hi");
}
public static void main(String[] args)
{
abcc=new abc();
c.abc();
}
};

intput and output

output:hi

For the final variables reassignment is not possible.

class Test
{
public static void main(String[] args)
{
final int a=10;
a=a+10;
System.out.println(a);
}
}

intput and output

output:The final local variable a cannot be assigned. It must be blank and not using a compound assignment

Every method present inside a final class is always final by default but every variable present inside the final class need not be final.

final class sup
{
int a=10;
void m1()
{
System.out.println("m1 method is final");
System.out.println(a+10);
}
public static void main(String[] args)
{
sup t=new sup();
t.m1();
}
}

intput and output

output:m1 method is final 20

final class program

final class Test
{
int a=10;
void m1()
{
System.out.println("m1 method is final");
System.out.println(a+10);
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
}

intput and output

output:20