Tuesday, April 22, 2014

Non-access modifier - final,part3

Scenario 5 : Using final with Class
  1. If we use final with Class then we restrict other class from extending that class, means final means end point of inheritance tree.
  2. To create a final class we need to use final keyword with class declaration.
  3. If we can not inherit the class then that means we can not use overriding concepts also.
  4. Apart from using final, there is another way by which we can restrict inheritance that is by making all the constructor private.( i will explain this concept in constructor topic and singleton design pattern)
  5. Making class final plays a vital role when we want to create an immutable type in java( i will explain immutability in another post).
  6. In JavaSE library , java.lang.String is best example where String class is declared final.
  7. In JavaSe library , java.lang.Runtime is class which have used private constructor.
Example :
package in.technoscience.finalclass;

public final class SomeClass { // class declared with final keyword
 public static void main(String[] args) {
  System.out.println("hello");
 }

}
public class AnotherClass extends SomeClass { // compiler unhappy

}

Here compiler will be unhappy, it will suggest you that if you want to extend the SomeClass then remove the final keyword from class declaration.

Note: We can not use abstract and final together with class declaration as the whole purpose of abstract is to be extended.

Scenario 6: Final methods in class
  1. when we use final with methods in any class, then we allow inheritance but we prevent our methods from being overridden.
  2. we can not override final method in extending class to write our own logic.
  3. Here also we can not use abstract and final together with method,because abstract method means we need to override that method by extending the abstract class.
One example of a situation in which making a method final is the proper route to take is when a read-only property is used:
 
package in.technoscience.finalclass;

public class FinalMethod {
 private final String name;

 protected FinalMethod(final String name) {
  this.name = name;

 }

 public final String getName() {

  return this.name;

 }

}
In this example, the name property is set at construction time and can never be changed and we never want that a subclass to hide this property (which it could by declaring its own name property if getName( ) wasn't final).
This is a good reason to make a method final. By making getName( ) a final method, we can guarantee that the user of subclasses of this object will always call this method(not own method overridden in subclass) when that executes getName( ). 
In the JDK, the method getClass( ) in java.lang.Object is final for this very reason.

No comments:

Post a Comment