final:
1. final(lowercase) is a reserved keyword in java.
2. We can’t use it as an identifier as it is reserved.
3. We can use final keyword with variables, methods and also with classes.
4. The final keyword in java has different meaning depending upon it is applied
to variable, class or method.
final Variable:
1. The value of final variable cannot be changed once initialized.
2. If we declare any variable as final and if we try to modify its value, then we
get the compile Time Error.
Example:
public class Test {
final int a=7;
int b=5;
Test(){
b=b+1;
// if you try to modify the value of final variable
its give compile time error that the final field
Test.a cannot be assigned
// a=a+1;
}
public static void main(String[] args) {
Test t=new Test();
int c=2;
c=c+1;
System.out.println("a: "+t.a);
System.out.println("b: "+t.b);
System.out.println("c: "+c);
}
}
Output:
a: 7
b: 6
c: 3
final method:
1. The final method cannot be overridden by a subclass. Whenever we declare
any method as final, then it means that we can’t override that method.
2. If we try to override the final method then we get Compile Time Error.
3. Note: If a class is declared as final then by default all of the methods
present in that class are automatically final but variables are not.
Example:
public class Parentclass {
final public void finalmethod()
{
System.out.println("final method of parent class");
}
public void testmethod()
{
System.out.println("non-final method of parent class");
}
}
public class Childclass extends Parentclass{
public void testmethod()
{
System.out.println("Overriding a non-final testmethod
of parent class");
}
// If try to override the final method throw Compile error:
// Cannot override the final method from Parentclass
// public void finalmethod()
// {
// System.out.println("Overriding a non-final
testmethod of parent class");
// }
public static void main(String[] args) {
Childclass c=new Childclass();
c.testmethod();
c.finalmethod();
}
Output:
Overriding a non-final testmethod of parent class
final method of parent class
final class:
1. Whenever we declare any class as final, it means that we can’t
extend/inherit that class means we can’t create subclass of that class.
2. If we try to extend the final class then we get Compile Time Error.
Example:
final public class Parentclass {
// variables
// methods
}
// when we try to extend the final class then will get
compile time error that: The type Childclass cannot subclass
the final class Parentclass.
public class Childclass extends Parentclass{
// variables
// methods
}