Re: Does package level access apply to multiple source files?
Steve wrote:
I read that classes within the same package can access each others
functions
if their visibility is at least package-private, a.k.a. "default". They
cannot access each other's private methods.
as if the were their own.
Only if they extend the other class, otherwise they have to access the method
through the other class or an instance thereof.
This seems to be case when all of the classes are in the same source
file.
It's not the "same-source-fileness" but that the classes all have
package-private or public access, and of necessity are all in the same package.
However, I tried experimenting with 2 classes, separate source files,
same directory, same package. When I try to access a funciton, just
by typing the function name from one class in another file the
compiler tells me it can not find that function.
Because it's the method of another class, not a method of the calling class.
I am misinterpreting package level access?
Yes. See the example below.
printdude1968@gmail.com wrote:
It depends on how a class is defined. If you have a class foo in one
file and another class bar in another file
and bar extends foo, then bar can access all the methods of foo that
are not restricted. I think what you are
meaning is that if class foo and class bar are in separate files, then
can foo access the methods of bar and vice-versa.
My answer would be no, although, foo could instantiate bar inside of
it, but as far as foo having direct access to the methods,
I don't think so.
Correct.
class Foo
{
private static final String DESCRIP = "Foo class";
/* pp */ static String getDescrip() { return DESCRIP; }
private String name;
/* pp */ String getName() { return name; }
/* pp */ void setName( String n ) { name = n; }
}
class Bar
{
public static void main( String [] args )
{
Foo foo = new Foo();
foo.setName( "test foo" );
System.out.println( Foo.getDescrip() );
System.out.println( foo.getName() );
}
}
The usual rules of class reference for static and instance reference for
instance methods apply; one class can't just go using methods from another
class like it owns them.
--
Lew