Search This Blog

Tuesday, 30 October 2012

final keyword in java and android

final is very common keyword to discussion in Java. final used in different places with different meanings. but its inherit meaning remains same. Let discuss some case where we need to use final.

1) To prevent the inheritance  : Let have two class A and B. A extends by B. and it worked fine

 public class A {
  public void prind() {
   System.out.print("You can inherit me");
  }
 }
 public class B extends A{
  @Override
  public void prind() {
   super.prind();
  }
 }

But if you changes prind() method to final then you can not override this method in B class

 public class A {
  public final void prind() {
   System.out.print("You can not inherit me");
  }
 }
 public class B extends A{
  @Override
  public void prind() {  //   Cannot override the final method from A
  super.prind();                //   Quick fix -> remove final 
  }
 } 
 
2) Using as constant : a variable followed by final keyword works as a constant. you can not re assigned values inside this variable
                        private final int m = 10;
but now you can not re assign value inside m.if you do this, it will show compile time error
                  m = 10;         // Compile error ->The final field m cannot be assigned
         
But it will be exceptional when we talk about one Array followed by keyword final
            private final int[] a = new int[5];
assigning values to index of a is valid and works well
            this.a[0] = 30; // Successfully worked


Wait wait........Explain a bit - while creating private final int[] a = new int[5], we assign array a to size of 5. So its final now. we can not changes size of array. But the memory slot we assign for each element of array is not constant we can changes its values
so this.a[0] = 30; is valid but
        this.a=new int[10];          is invalid

Finally it works same for array also

No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code