lrod408
lrod408

Reputation: 135

command line error when trying to use java package

I'm learning java packages in school and I'm able to create and use my package on netbeans perfectly but cannot do it from the lubuntu command line. I get an error: could not find or load main class. Here is the code but I know this is not the problem since it works perfectly in netbeans

    package animals;

    public class MammalInt implements Animal
    {

     public void eat()
     {
      System.out.println("Mammal eats");
     }

     public void travel()
     {
      System.out.println("Mammal travels");
     } 

     public static void main(String args[])
     {
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
     }
    } 


     package animals;

     interface Animal 
     {
      public void eat();
      public void travel();
     }

I first compile Animal.java and put the Animal.class file into a directory animals. I then compile MammalInt.java. If I do not put the Animal.class file in a animals directory it will not compile MammalInt.java . After I have both class files into the animals directory I do java animals/MammalInt and get the error: cannot find or load main class. I also have doe java MammalInt and get the same error. This is really frustrating. Please help.

Upvotes: 2

Views: 403

Answers (1)

Thirler
Thirler

Reputation: 20760

When compiling (a set of files) you need to use the path.So use /

javac animals/*.java

When running the Java class, you need to specify the Java name of the class.

In your case this is done as follows:

java animals.MammalInt 

This says you want the class MammalInt in the package animal. Depending on your installation you also need to add your current directory to your classpath (this is where java looks for .class files), resulting in:

java -cp . animals.MammalInt 

Note that you run all commands from the root of your source code tree. This means the directory that contains the directories for your packages. So if you have the following direcotries:

project/
project/animals/
project/animals/Animal.java

Then run the commands from the project/ directories.

Upvotes: 1

Related Questions