Reputation: 305
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?
Upvotes: 4
Views: 2725
Reputation: 21004
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.
Upvotes: 4
Reputation: 1552
Method Overloading is done in same & child class, while Overriding is done in child class only. We do override other Object class methods (equals(), hashCode() etc.) due to their significance, but never overload any of these methods.
So while you CAN overload the finalize()
method, it would be just like a new method in your child class, and wouldn't be considered by JVM (as a finalize() method really).
Upvotes: 2
Reputation: 766
While overloading finalize() is possible just like any other method, I don't see the point to do that. JVM will not invoke that method and even if this is not your goal, overloading it would just generate confusion.
If you meant overriding on the other hand, it could make more sense but it is strongly a not recommended approach. There are many downsides of using finalizers. For more info you can find some good advice (Item 7) in Joshua Bloch's "Effective Java" book. It basically says, avoid using finalizers.
Upvotes: 0
Reputation: 4434
You can overload the finalize method without any issue. Here is another example:
public class FinalizeOverloader {
protected void finalize(String userId) {
System.out.println("I could overload finalize...");
}
public static void main(String[] args) {
FinalizeOverloader fO = new FinalizeOverloader();
fO.finalize("AbC");
}
}
Upvotes: 1
Reputation: 7501
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();
}
Upvotes: 7