I want to create an object class (PERSON) inside the main class in java for some reasons (as far as I know such an action is possible without need to use a further file)
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John");
System.out.println(myObj.getName());
}
}
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
but I’m getting the following error
Main.java:9: error: class Person is public, should be declared in a file named Person.java
public class Person {
^
1 error
>Solution :
If you want to do this without creating another file, you can create Person as an inner class: https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html.