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 */

publicclass SuperClass {

@Override

protectedvoid 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 */

publicclassSubclass extends SuperClass{

@Override

protectedvoid 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();

}

}

publicstaticvoid 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 becausefinalize 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 */

publicclass MyClass1 {

@Override

protectedvoid finalize() throws Throwable {

//....

}

}

MyClass2 is in package com.ankit2

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