TMOTTM
TMOTTM

Reputation: 3381

Can't use a Java class in another file

Can't find a solution to this problem.

Guitar2.java:

public class Guitar2
{
    private String serialNumber;

    public Guitar2(String serialNumber)
    {
        this.serialNumber = serialNumber;
    }

    public String getSerialNumber()
    {
        return serialNumber;
    }
}

Inv2.java:

import java.util.List;
import java.util.LinkedList;

public class Inv2
{
    private List guitars;

    public Inv2()
    {   
        guitars = new LinkedList();
    }

    public void addGuitar(String serialNumber)
    {
        Guitar2 guitar = new Guitar2(serialNumber);
        guitars.add(guitar);
    }
}

Both files are in the same directory, both are 755 and the directory is in the classpath. I get the error message:

[machine]me @ directory $ javac Inventory.java 
Inventory.java:18: cannot find symbol
symbol  : class Guitar
location: class Inventory
        Guitar guitar = new Guitar();
        ^
Inventory.java:18: cannot find symbol
symbol  : class Guitar
location: class Inventory
        Guitar guitar = new Guitar();
                            ^
2 errors

I read that if a file is in the same directory, classes from it can be used in other files in the same directory without any import statements. What's the problem here?

POST EDIT Output when using the above code:


[me]machine @ ricks $ javac Inv2.java 
Note: Inv2.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

I get the .class files of both .java files.

Upvotes: 0

Views: 975

Answers (3)

Ivaylo Toskov
Ivaylo Toskov

Reputation: 4021

Make sure both classes have the same package. Even if they are in the same directory, a different package could cause this problem. Type the same package or use an import and then try compiling with javac *.java

Upvotes: 0

Mifmif
Mifmif

Reputation: 3190

Try to compile Guitar.java first. then run your cmd . or try this : javac *.java

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53525

Run javac Guitar.java and only then (after it has been compiled and a Guitar.class was created) run javac Inventory.java

Upvotes: 3

Related Questions