Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can finalize() method be overloaded in Java

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?

like image 450
Saif Avatar asked Dec 10 '22 23:12

Saif


2 Answers

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();
}  
like image 163
Evan Knowles Avatar answered Dec 28 '22 08:12

Evan Knowles


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.

like image 32
Jean-François Savard Avatar answered Dec 28 '22 06:12

Jean-François Savard