In the following code, I am getting the output Hello. Can anyone explain why compiler is not reporting an error it I am calling a protected function outside the class and inheritance chain.
package sampleproject;
public class SampleProject
{
public static void main(String[] args)
{
Sample s=new Sample();
s.finalize();
}
}
class Sample
{
@Override
protected void finalize()
{
System.out.println("Hello");
}
}
Thanks.
protectedscope includes the package, as well as the class and subclass(es). Both your classes are part of the same package.I hope you’re not intending to call
finalize(), btw. That should be left to the garbage collector (and not relied on,. either!). See this answer for more info.