tags:

views:

51

answers:

4

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) { ... }

   public void setObjectProperty (CustomObject obj) { ... }

   //any other methods with public access level   
}
A: 

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.

helios
I could imagine that his class doesn't implement any interface, as you can clearly see from the code.
danben
I guess not :) but the code is only an example and he was looking for a difference. Anyway the answers refering to subclassing seem a lot more promising.
helios
A: 

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.

Drew Wills
+1  A: 

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.

Jim Kiley
How can I create subclass of Foo in another package?
Roman
Ha -- good point! Foo wouldn't be visible outside of its own package.
Jim Kiley
You can't create a subclass of Foo in another package or create an instance of it in another package because it wouldn't be "seen" by that package due to it's default access level.
Jon
+2  A: 

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)

idrosid
Note: Bar is in the same package as Foo
idrosid
First real answer
Roman