Saturday, 6 April 2013

Interview Question #7 What is final in java?

A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

If you want a variable to be owned by the class and not by it's individual instances(objects) and also you want the value of the variable to be constant you can declare it as static and final both.

 For Example
       private final static String name = "JavaForGeeks";

The concept is interpreted a bit different way for Objects, Collections. You can change the data inside the object/Collection but cannot make the reference(which is final) point to different Object.

For example

public class HelloWorld {
   
    String greetings;
   
    public String getGreetings() {
        return greetings;
    }
    public void setGreetings(String greetings) {
        this.greetings = greetings;
    }

}


Even if the HellowWorld instance is defined final you can call setter method of it's data.

    public static void main(String args[]){
        final HelloWorld hw = new HelloWorld();
        hw.setGreetings("test");  //allowed
        //hw = new HelloWorld(); //not allowed
    }



Same goes for Collections

    public static void main(String args[]){
        final List<String> myList = new ArrayList<String>();
        myList.add("Test");    //allowed
        //myList = new ArrayList<String>();    //not allowed
    }

 

No comments:

Post a Comment

t> UA-39527780-1 back to top