Final Keyword:
'final' can be applied to variables,methods and classes.
What happens if we declare variables or methods or classes as final ??
Usage of 'final' with variables:
We can't change the values of the variables which are declared as final.This is the way to declare the constants in java.If we try to change the value of a final variable then it results a compile time error as follows
class Final
{
public static void main(String args[])
{
final int a=10;
a=20
}
}
Usage of 'final' with methods:
We can't override the methods which are declared as final.If we try to override these methods then it results in a compile time error as follows
class Final
{
public static void main(String args[])
{
System.out.println("Main method");
}
final public void add(int a,int b)
{
System.out.println("Sum is"+(a+b));
}
}
class Subclass extends Final
{
public void add(int a,int b)
{
int c=a+b;
}
}
Usage of 'final' with classes:
We can't inherit the classes which are declared as final.If we try to override these methods then it results in a compile time error as follows
final class Final
{
public static void main(String args[])
{
System.out.println("Main method");
}
}
class Subclass extends Final
{
public void add(int a,int b)
{
int c=a+b;
}
}
0 comments:
Post a Comment