Lets discuss one of the important keyword final that appears in java.final can be used with respect to variables,methods and class.
final with respect to variables:
A variable that is declared s a final acts like a constant variable and do not entertain any further modifications.Example
import java.io.*;
class Code
{
final int var=10;
void methodA()
{
var=15;
System.out.println(var);
}
public static void main(String args[])
{
Code c=new Code();
c.methodA();
}
}
Output:
Code.java:6: error: cannot assign a value to final variable var var=15;
Initialization of final variables:
A final variable that is not initialized at the time of declaration is called a blank final variable. We can only initialize such variables inside the constructor of the class.Example:
import java.io.*;
class Titans
{
final int var;
Titans()
{
var=10;
}
void methodA()
{
System.out.println("value of var is "+var);
}
}
class Code
{
public static void main(String args[])
{
Titans t=new Titans();
t.methodA();
}
}
Output:
value of var is 10A final variable that is declared as a static final and didn't get initialized at the time of the declaration,then it must be initialized only in the static block.
Example:
import java.io.*;
class Code
{
static final int var;
static{
var=20;}
public static void main(String args[])
{
Code c=new Code();
System.out.println("value of var is "+c.var);
}
}
Output:
value of var is 20
final with respect to methods:
A method prefixed with final cannot be overridden.Example:
import java.io.*;
class Code
{
final void methodA()
{
System.out.println("This methodA() is in class Code");
}
}
class Titans extends Code
{
void methodA()
{
System.out.println("This methodA() is in class Titans");
}
public static void main(String args[])
{
Titans t=new Titans();
t.methodA();
}
}
Output:
Titans.java:11: error: methodA() in Titans cannot override methodA() in Code void methodA()
final with respect to class:
Whenever a class is declared as final it cannot be inherited.Example:
import java.io.*;
final class Code
{
int var=10;
}
class Titans extends Code
{
public static void main(String args[])
{
Titans t=new Titans();
System.out.println(t.var);
}
}
Output:
Titans.java:6: error: cannot inherit from final Code class Titans extends Code
No comments:
Post a Comment