Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create object class inside Main class in java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading