-1

I just started with Java package and wanted do something easy first. So i did 2 classes and I get an error why Im creating an object of the second class.

Error: Could not find or load class main 

I get this error using

javac *.java

Here is my code

package person;
public class Main {


public static void main(String[] args) {
    Person p1 = new Person();
    p1.setFirstName("John");
    p1.setAge(20);
    System.out.println(p1.getAge());
}

}

And second class

package person;
public class Person {

private String firstName;
private int age;

public Person() {
}
public void setFirstName (String n)
{
    firstName = n;
}
public void setAge(int a)
{
    age = a;
}
public int getAge()
{
    return age;
}

}

when I compile file one by one i get this error

Error: cannot find symbol
Person p1 = new Person();

And it is pointing at Person before p1 and Person after new. All files are in the same file, so i dont know whats the mistake here.

Musrky2
  • 1
  • 1
  • Possible duplicate of [How to compile packages in java?](http://stackoverflow.com/questions/10546720/how-to-compile-packages-in-java) – starcorn Apr 21 '17 at 22:56

2 Answers2

0

You are not importing Person in your file that contain the Main class.

Mateus Luiz
  • 756
  • 7
  • 20
0

Here is a short answer tailored for your specific use-case:

  1. Make sure that both source files are in the same directory AND that the directory is named person.

  2. Make sure that source filenames match the class names; i.e. the Person class is in Person.java, and Main is in Main.java. Case sensitivity is important.

  3. Change directory to the parent directory of person.

  4. Compile the code with this command:

      javac -classpath . person/*.java
    

    If there are compilation errors, fix them and repeat ... until the code compiles without errors.

  5. Run the compiled classes as follows:

      java -classpath . person.Main
    

For a more general Answer, read this:


Building / running from the command line like this is not the recommended way to do things. You are better off learning to use 1) an IDE like Eclipse or NetBeans and 2) a build tool like Ant, Maven or Gradle.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216