user1058795
user1058795

Reputation: 249

Java default class access of package-private works like public

As stated in many places, a class yields a package-private access level, which means such a class can only be accessed by others is the same package. I don't know many things about packages, but I suppose knowing you add "package x" at the start of a file is enough knowledge to pose my question.

I've made a file with a class ingredient. Another file contains

public class cooking{ 
    public static void main(String[] args) {.....

There's no package declaration anywhere. Still, my program compiles the two files successfully, and also runs so. What am I missing? Shouldn't the cooking class NOT be able to see ingredient?

Upvotes: 0

Views: 521

Answers (4)

Marton Tatai
Marton Tatai

Reputation: 190

As laid out in the Java Language specification your classes are part of an (the) unnamed package, that's why they can see each other.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.4.2

Upvotes: 1

xtraclass
xtraclass

Reputation: 445

if you do not add a package statement to java classes, then those classes are in the same package = the so-called "default" package. and therefore those classes have access to each other no matter if you define the classes as public or not.

public class A

= this class A is visible in all packages

class B

= this class B is visible only by classes in the same package as B

Upvotes: 1

Brandon Buck
Brandon Buck

Reputation: 7181

Classes can see other classes in the same directory without import statements. Packages are ways to to organize your code and essentially just directories in the application folder. All classes can see other classes within the same class without the need for importing, it's when different packages are defined such as your structure being:

src
 |
 +- Cooking.java
 |
 +- utilities
     |
     +- Ingredient.java

Of course your Ingredient file would be prefaced with package utilities; and if you tried to access it from cooking you'd get an error unless you had import utilities.Cooking; in the file. Package-private simply means that classes outside of the package (or folder) cannot see or access the file or it's Package-private properties.

Upvotes: 1

Your IDE (like netbeans or eclipse) compiles the code, because both classes are in the same project and it 'knows' that you mean that class.

Upvotes: 1

Related Questions