I have created a simple java project "DesignPatterns".
I created a file FacadePattern.java with the path being ~/DesignPatterns/Structural/FacadePattern/FacadePattern.java
My FacadePattern.java
class,
public class FacadePattern {
public static void main(String args[]) {
// Some code
}
}
But my editor (VSCode) gives me an error at the start of the file:
The declared package "" does not match the expected package "Structural.DecoratorPattern"
So upon clicking on quick fix, it added package Structural.FacadePattern;
in the first line.
So the final code became
package Structural.FacadePattern;
public class FacadePattern {
public static void main(String args[]) {
// Some code
}
}
But when I compile the above file using the command
javac FacadePattern.java && java FacadePattern
It is giving me the following error:
Error: Could not find or load main class FacadePattern
Caused by: java.lang.NoClassDefFoundError: Structural/FacadePattern/FacadePattern (wrong name: FacadePattern)
After searching a lot in the internet, I ran the following command:
javac -sourcefile ~/DesignPatterns FacadePattern.java && java FacadePattern
But no use, I am getting the same error.
Can anyone explain why my editor gave an error but code ran successfully before? and why wont it compile after adding "package Structural.FacadePattern;" line? and what is -sourcefile parameter in javac command? and how to run the code with successfully without errors in editor as well as the terminal?
CodePudding user response:
Stick to naming rules. Package names should be lowercase only. In your case, it should be
package structural.facadepattern;
Run the 'correct' class. Because your class is not inside 'the base folder' aka the 'default package', you have to prefix the class with its package name:
java Structural.FacadePattern.FacadePattern
or ratherjava structural.facadepattern.FacadePattern
if you use the proper case for packages.