Friday, 21 February 2014

final Classes and Methods

final methods
If a method declared as final, then it can't be overridden by sub class.

Example
class SuperClass{
 final void print(){
 }
}

class SubClass extends SuperClass{
 void print(){
 }
} 

SubClass trying to override the method print() which is final. So when trying to compile the program, SubClass, then compiler throws the below error.
 SubClass.java:2: error: print() in SubClass cannot override print() in SuperClass
    void print(){
    ^
    overridden method is final
    1 error

Same is applicable to static classes also.
class SuperClass{
 final static void print(){
 }
}
 

class SubClass extends SuperClass{
 static void print(){
 }
}

When you tries to compile the SubClass.java, compiler throws the below error.
    SubClass.java:2: error: print() in SubClass cannot override print() in SuperClass
    static void print(){
    ^
    overridden method is static,final
    1 error

final classes
Any class which is declared as final, can't be extended. Try to extend a final class causes a compiler error.

Example
final class SuperClass{

}

class SubClass extends SuperClass{

}


When you tries to compile the SubClass.java, compiler throws the below error.

SubClass.java:1: error: cannot inherit from final SuperClass
    class SubClass extends SuperClass{
    ^
    1 error

Some Points to Remember

1. Both the private and final methods can't be overridden.
Example
class SuperClass{ 
 private void print(){ 
  System.out.println("I am super class"); 
 } 
}
   
class SubClass extends SuperClass{
 void print(){
  System.out.println("I am sub class");
 }

 public static void main(String args[]){
  SuperClass obj = new SubClass();
  obj.print();
 }
}


When you tries to compile the SubClass.java, compiler throws the below error.

 SubClass.java:8: error: print() has private access in SuperClass
            obj.print();
            ^
            1 error
         
2. Can I make private method as final ?
Since private already implies that a subclass may not override a method, declaring a private method to be final is redundant. It won't cause any problem to your program, Program compiles fine.


Final Variables                                                 Abstract methods and Abstract classes                                                 Home

No comments:

Post a Comment