Final Keyword tutorial Report
By:-Ravindu Perera 2014259
Case 1
How to stop a variable from changing?
public
class
Tutorial {
public
static
void
main(String[] args)
{
Test
test = new
Test();
System.out.println(test.p1);
}
}
class
Test {
public
final
double
p1 = 3.14;
Test()
{
p1
= 2.14;//due to the finall
keyword the intialised
value cannot change
}
}
here
because the variable made final so we cannot change the variable it
is made a constant.
Case
2
How
to stop a method from being overriden when it is inherited?
public
class
finalMethod {
final
void
data() {
System.out.println("I
have 1 GB");
}
}
class
tre extends
finalMethod {
void
data()
{//here the method is not being allowed to ovrride
System.out.println("I
have 5GB");
}
public
static
void
main(String []args){
}
}
because
the method uses the keyword final the extened class will be not allow
to overrride the method as final keyword stops it.
Case
3
How
to prevent a class from being inherited?
public
final
class
finalMethod {
final
void
data() {
System.out.println("I
have 1 GB");
}
}
class
tre extends
finalMethod
{//the final keyword prevents
inheritance
void
data() {
System.out.println("I
have 5GB");
}
public
static
void
main(String []args){
}
}
in
this code the final keyword is being used to prevent the superclass
being inherited to the subclass so an error message is being shown.