0

Not able to call finalize() method on different Object. I am using Eclipse .

I have created object of StringBuilder

StringBuilder sb= new StringBuilder("abc");
sb.finalize(); // compile time error The method finalize() from the type Object is not visible    

I have created a 2 classes Test and MyTest with main method in each

  public class Test {

          public  static  void main throws Throwable(String [] args ){

                  Test t= new  Test();
                  t.finalize();    //ok no  error

                  MyTest mt= new MyTest();

                  mt.finalize() // compile time  error  The method finalize() from the type Object is not visible
          }
    }

I have some questions on my mind:

1) As object is super class of all java classes.finalize method must be available because finalize method is protected. Then why eclipse is giving such error ?

2) Is this a bug in eclipse ?

please someone elaborate this concept in details.

Simulant
  • 19,190
  • 8
  • 63
  • 98
sar
  • 1,277
  • 3
  • 21
  • 48

2 Answers2

4

If you would take a look at the API for Object, you would notice that the method has a visibility of protected NOT public.

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package. source

With protected only classes within the same package or sub-classes are allowed to access the method anything else will result in a compiler error.

public class Test {

    public  static  void main throws Throwable(String [] args ){
        Test t= new  Test();
        t.finalize();    //ok no  error
    }
}

Here you are calling finalize from within the class Test and as such finalize is visible as Test is, implicitly, a subclass of Object.

public class Test {

    public  static  void main throws Throwable(String [] args ){

        MyTest mt= new MyTest();
        mt.finalize() // compile time  error  The method finalize() from the type Object is not visible
    }
}

Here you are calling the method on the class MyTest and as this isn't from within the same class nor from within the java.lang package the finalize method isn't visible, hence a compiler error.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
1

Object#finalize() is not supposed to be invoked externally.

From the Javadocs

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
Dhrubajyoti Gogoi
  • 1,265
  • 10
  • 18