Final methods:

Requirement: I have function in base class which want to share with derived classes but they should not be able to override that function.
	   class Base
	   {
  	        public final void fun()
  	        {
  	         System.out.println("Base function");
  	        }
	   }
	  class Der extends Base
	   {
	      public void fun()   //cannot override the final method from base
	      {
  	       System.out.println("Der function");
   	        fun();
 	      }
             }
Requirement: I have a class and I don't want any one to inherit that class.

Final classes:

	  final class Base
	  {
   	     public void fun()
    	     {
     	          System.out.println("Base Function");
    	     }
	    class Der extends Base // compile error
	    {
  	     public void test()
  	      {

  	       }
	  }
Note: --> By default all the function of final class become final methods. --> Final classes are also called as immutable classes, because nobody can change the definition of that class.

Examples for immutable classes:

--> All wrapper classes for primitive data types are immutable. int - Integer boolean - Boolean char - Character String, string buffer, string builder are immutable classes.

Final Objects or Immutable Objects:

--> Nobody can change the state of the immutable object. --> States means "variables".
     	class Test
	{
   	    private final int i;
   	    public Test(int t)
  	    {
    	        i=t;
  	    }
	    public void display()
	    {
   	        System.out.println(i);
  	     }
	    public void change(int z)
	    {
   	       i=z;
 	     }
	 }
	public class MainClass
	 {
 	       public  static void main(String[ ] args)
 	       {
    	           Test  t= new Test();
    	           t.change(20);
  	       }
	 }

Creating immutable objects:

-->Make all your variables in the class as either "private" or "final". -->Do not give any public function to modify your private variables. -->If you are giving any setters & getters then make your variables as "final".
	 class Test
	  {
  	      private final int i;
              public Test(int t)
	      {
   	          i=t;
	       }
	  }
	 public class Mainclass
	   {
  	      public static void main(String[] args)
	      {
	       Test t= new Test(10);
	       }
	   }
finalclasses
This should give compiler error:
	     class Test
	     {
	         int i;
 	         private Test()
  	         { 
    	            i=10;
   	          }
	        public void change()
 	        {
    	              i =z;
 	         }
	      }
	    class Der extends Test
	    {
   	      public Der()
   	      {
    	          super();
  	       }
	    }