I've read somewhere that every method can be overloaded.
finalize()
is a method of course. But while searching I also found that you cannot overload this method.
So the Question is Can we overload the finalize() method? If yes then how is it implemented?
Yes, you can. But the overloaded version won't be called by the JVM.
@Override
protected void finalize() throws Throwable
{
super.finalize();
}
protected void finalize(String lol) throws Throwable
{
finalize();
}
You can overload the finalize
method, this would compile successfully :
public class Test
{
public void finalize(String hi)
{
System.out.println("test");
}
}
However it won't be called by the Garbage collector and JVM as it will call the one with no parameters.
GC and JVM will only and always call the finalize
with the signature
protected void finalize() throws Throwable
Workaround
You could simply override finalize
and make it call the method with parameters :
public class Test
{
public static void main(String args[])
{
new Test();
System.gc();
}
@Override
public void finalize() throws Throwable
{
super.finalize();
this.finalize("allo");
}
public void finalize(String hi)
{
System.out.println(hi);
}
}
That would print allo
. That way you could call finalize(String hi)
where you want, and the GC would also call it as you overrided finalize()
to call it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With