For example, this works just fine.
package OOPS;
public class Pen {
public static void main(String[] args) {
PenMaker linc = new PenMaker();
linc.color = "blue";
linc.type = "ballpoint";
linc.write("Hi mom!");
linc.printTypeAndColor();
}
}
class PenMaker {
String color;
String type;
public void write(String str) {
System.out.println(str);
}
public void printTypeAndColor() {
System.out.println("I'm a " this.type " pen of " this.color " color.");
}
}
But I want to keep my prototype class at the top of the file. Something like this.
package OOPS;
class PenMaker {
String color;
String type;
public void write(String str) {
System.out.println(str);
}
public void printTypeAndColor() {
System.out.println("I'm a " this.type " pen of " this.color " color.");
}
}
public class Pen {
public static void main(String[] args) {
PenMaker linc = new PenMaker();
linc.color = "blue";
linc.type = "ballpoint";
linc.write("Hi mom!");
linc.printTypeAndColor();
}
}
But this doesn't compile and says "error: can't find main(String[]) method in class: OOPS.PenMaker".
In both cases the file name is Pen.java .
CodePudding user response:
both codes are correct and compile and run successfully
as long as your file has one public class (in this case Pen) it should compile it doesn't matter the order.
I would suggest to resave your second code and close your IDE or console and reopen again
CodePudding user response:
The argument you pass to java
(the executable) is a fully qualified classname. In your second snippet, the main
method is in the class named Pen
which is in the package named OOPS
, which therefore makes that class's fully qualified name OOPS.Pen
. There's also the OOPS.PenMaker
class, but it has no main
method, which is exactly what your error says.
To run that main method, you'd type java OOPS.Pen
. Because that class has a main
method. The error message you are getting when you run java OOPS.PenMaker
kinda spells this out. In general, assume error messages are telling you what's wrong.