'How do packages work in Java, specifically when using VSCode?
I'm trying to create a folder called 'a' within a project that I'm currently in in VSCode. Within this folder, I am trying to create a file called Solution.java. When I create this file, I get an error saying "The declared package "" does not match the expected package "a"".
Resolving this issue is easy (just declare package a in Solution.java), but when I go an open the folder 'a' in a different VSCode window, I no longer get the package error in the Solution.java file within folder 'a', meaning I no longer need to declare a package.
Why is this? Why would changing the root project folder in VSCode change the need to declare a package?
Solution 1:[1]
You should add package
statement like below to the top of the Solution.java.
package a;
Solution 2:[2]
That's because the identity of A changed.
VS Code recognizes the folder currently opened as project folder:
When you open A as the project folder, you can definitely create java files under it, and no statement needed;
When you open KICKSTART as the project folder, folder A turns to be a package and if you want to create java files under it, you should follow the java developing rules and add package a;
on the top line of .java files which under folder a.
More information about package, please refer to Java-Package.
Solution 3:[3]
In order to fix the issue you must declare a package,
Syntax:
package package_name.sub_package_name;
(Declare a subpackage when you've created the file in a folder inside another folder) where the name of the package is the same as the folder in which you've created your java programme file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Liquidpie |
Solution 2 | Molly Wang-MSFT |
Solution 3 | Mr. T-REX |