Why finalize method is protected in java - An explanation with programs


finalize method for object can be called from some other class outside the package with inheritance


SuperClass  is in package com.ankit1
package com.ankit1;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class SuperClass {
   @Override
   protected void finalize() throws Throwable {
          try {
                 System.out.println("in finalize() method of SuperClass, "
                              + "doing cleanup activity SuperClass");
          } catch (Throwable throwable) {
                 throw throwable;
          }
   }
}


SubClass  is in package com.ankit2
package com.ankit2;
import com.ankit1.SuperClass;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class Subclass extends SuperClass{
   @Override
   protected void finalize() throws Throwable {
          try {
                 System.out.println("in finalize() method of Subclass, "
                              + "doing cleanup activity of Subclass");
          } catch (Throwable throwable) {
                 throw throwable;
          }finally{
                 super.finalize();
          }
   }
   public static void main(String[] args) {
          Subclass subclass = new Subclass();
          System.out.println("in main() method");
          try {
                 subclass.finalize(); //call finalize() method explicitly
          } catch (Throwable throwable) {
                 throwable.printStackTrace();
          }
         
   }
}
/*OUTPUT
in main() method
in finalize() method of Subclass, doing cleanup activity of Subclass
in finalize() method of SuperClass, doing cleanup activity SuperClass
*/

Subclass extends SuperClass. So, calling super.finalize() is valid because finalize method for object can be called from some other class outside the package with inheritance.



finalize method for object can’t be called from some other class outside the package without inheritance


MyClass1 is in package com.ankit1
package com.ankit1;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass1 {
   @Override
   protected void finalize() throws Throwable {
          //....
   }
}


MyClass2 is in package com.ankit2

MyClass1 does not extends MyClass2. So, calling finalize() method by creating instance of MyClass1 in MyClass2 is invalid (any attempt to do so will cause compilation error) because finalize method for object can’t be called from some other class outside the package without inheritance.



RELATED LINKS>

final keyword in java - 20 salient features

finalize method in java - 13 salient features


No comments:

Post a Comment