Question

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.

Était-ce utile?

La solution

protected scope 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.

Autres conseils

protected makes a method visible in the same package

This might help: Controlling Access to Members of a Class

protected members can only be accessed by members of their own class, that class's subclasses or classes from the same package.

From here

You have a file called SampleProject.java inside the package sampleproject. SampleProject.java contains two classes defined namely SampleProject and Sample. So when you compile the file SampleProject.java , you will see SampleProject.class and Sample.class in the same folder. So they are in same package (because compiler inserts package as samplepackage for the Sample.class, hence calling the finalize method succeeds.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top