2

Actually I was going through The Java Language Specification and I found a strange sentence from which I couldn't come to a conclusion. Since I'm not a native English speaker.

If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
• The type is referred to by code in other compilation units of the package in which the type is declared.
• The type is declared public (and therefore is potentially accessible from code in other packages).

could someone please explain the line which is marked in bold by giving an example .Thank you in advance.

MRM
  • 165
  • 6

2 Answers2

0

In Java a compilation unit is essentially a file.

If you have declared a type (e.g. a class) that is used in another file than it is declared in (which is usually the case), then it is a compilation error if a file, named by the type name + extension, cannot be found.

I.e.: When importing a class or other type, Java must be able to translate its package+name into a file name that must exist.

0

You have Class CustomObject in package com.example

package com.example;
public class CustomObject {
    String firstName;
    String lastName;
}

This class can be accessed from another class in same package, Note, as CustomObject is public class, it can be accessed from any class within the project. In case it is declared just as class CustomObject then it can be accessed only within package com.example

package com.example;

public class Test {
    
    public CustomObject myObject; 
    
    public static void main(String[] args) {
        myObject = new CustomObject();
        
    }

}
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24