Friday, 10 March 2017

Use of Final Keyword in java

Case 1: A final class cannot be inherited.
final class Test{
      
}
public class Test01 extends Test {

       public static void main(String arg[]){
      
   }
}
CTE- The type Test01 cannot subclass the final class Test

Case:-2- A final method cannot be overriden-
class Test{
               
                public final void print(){
                                System.out.println("Test");
                }
               
}
public class Test01 extends Test{

@Override
public void print(){
                                System.out.println("Test01");
                }
               
public static void main(String arg[]) {
               
   }
}
CTE:- Cannot override the final method from Test

public void final print() {
              System.out.println("Test");
       }
CTE-Syntax error

Case 3: A final variable can only be initialized once.

final int i=10;
        i=30;--------CTE

Case 4: final variables can be inherited.

class Test{
        final int i=10;
}
public class Test01 extends Test
  {
       public static void main(String arg[])
       {
      Test01 tt= new Test01();  //Sub class
      System.out.println(tt.i);
   }
}
O/P-10


                                

No comments:

Post a Comment

Download Android SDK

Download Android SDK tools Follow me on Instagram - https://www.instagram.com/virenautomationtesting/ Follow me on Twitter- https://twitt...