Thursday, 19 January 2012

Final Class & Final Method

Final Class:

A subclass is inherited from a super class. But in some situation if we want to prevent the inheritance of a class then we use final class.

For example

final class abc{
void printSqure(int x){
System.out.println(x*x);
}
}

class FinalExample{
public static void main(String args[]){
abc obj= new abc();
abc.printSqure(5);
}
}

This program will output 25 If we try to inherit a subclass from abc then the compiler give us an error.

Final Method:



 



Methods in a class can be protected from overriding methods in the subclasses by declaring the method as final.



For example



class abc{
final void printSqure(int x){
System.out.println(x*x);
}
}

class FinalExample{
public static void main(String args[]){
abc obj= new abc();
abc.printSqure(5);
}
}

If we try to override the printSqure() method in any subclass of abc then we will get an error.

No comments:

Post a Comment