Reputation: 407
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.
Upvotes: 1
Views: 98
Reputation: 3288
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.
Upvotes: 0
Reputation: 19209
protected members can only be accessed by members of their own class, that class's subclasses or classes from the same package.
From here
Upvotes: 0
Reputation: 11097
protected
makes a method visible in the same package
This might help: Controlling Access to Members of a Class
Upvotes: 0
Reputation: 272437
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.
Upvotes: 4