Is there any difference between default (package) and public access level of methods in class with default (package) access level?
The same question in code:
class Foo {
int getIntProperty () { ... }
CustomObject getObjectProperty () { ... }
void setIntProperty (int i) { ... }
void setObjectProperty (CustomObject obj) { ... }
//any other methods with default access level
}
VS
class Foo {
public int getIntProperty () { ... }
public CustomObject getObjectProperty () { ... }
public void setIntProperty (int i) { ... }
开发者_StackOverflow public void setObjectProperty (CustomObject obj) { ... }
//any other methods with public access level
}
There is a difference when you subclass Foo:
public class Bar extends Foo {
}
then try in another package:
new Bar().getIntProperty ()
It will compile at the second of your examples (all methods public) but not at the first (all methods default access)
From http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html it looks like the members not set public, in the first example, would not be visible to subclasses of Foo, while the members set public, in the second example, would be visible to subclasses of Foo.
Implementing interfaces
I only can imagine your default access class implements some interface. Then you'll need the public access methods for implement it (your default access class is then accessed outside the package, via the interface).
Like any private/protected/anonymous implementation of an interface.
Java Language has to support it.
Edit
Imagine you create an instance and pass it over an outsider class (as an Object).
I'm not sure about reflection access control, but may be the outsider class cannot access via reflection (outside the package) the default methods. And if they're public you can.
Yes & no.
There's no meaningful difference -- at least when it comes to other classes accessing the method -- in the example you give. But sometimes you have...
public interface Bar {
CustomObject getObjectProperty ();
}
And Foo implements Bar
, in which case public is necessary, even within a package-private Foo.
This is an example of package level class with public level method()
in order to ensure the access level can't be more restrictive than the overridden method's.
Assume public level super class has public access level methods. and package level sub class wants to inherit that super class then also you need public level methods. for eg
public class A { public void method() }
class B extends A { public void method() }
精彩评论