Friday, May 7, 2010

Why Clone() and finalize() methods in Object class are protected?

Clone() and finalize() are the only two protected methods in Object class.
Why is it required after all?
Object class is superclass of all the classes in Java so even if we make it protected,
by default, every class will have its access so if we see - public or protected
does not matter.
But if they were left "public" it has its drawback - Any class anywhere can make an
object of our class & can directly access these two methods. So unwanted calls to
these methods are possible
Here are two code examples of finalize() method to make this concept clear,
same is true for clone() method

Example when finalize() is taken as public method -

package com.check; // Package is different 
public class CheckFinalize{
         protected void finalize(){  //can't be declared protected if 
                 //it is public in Object class
System.out.println("Check Finalize");
                //code to close connection for our class
}
         public void update(){
                // code to update data at connection
        }



package com.access; // This package is different from the upper class package
public class CallFinalize{
        public static void main(String[] args){
               CheckFinalize cf = new CheckFinalize();
               cf.finalize();
               cf.update();  // will throw IOException as connection is closed
       }
}

Example after finalize() is made protected -


package com.check; // Package is different 
public class CheckFinalize{
         protected void finalize(){  //declared protected as it 
                //is protected in Object class
System.out.println("Check Finalize");
                //code to close connection for our class
}
         public void update(){
                // code to update data at connection
        }

package com.access; // This package is different from the upper class package

public class CallFinalize{
        public static void main(String[] args){
               CheckFinalize cf = new CheckFinalize();
               // cf.finalize();  this is not possible now as finalize is protected 
               cf.update();  // No Exception
       }
}


*Packages for these two classes are different.
Your feedback is welcome.