How can I import class from the same package in Java?

3.7k views Asked by At

How can I use one class from other class in the same package in the same directory? I have one class Utils:

package pl.jcubic;

public class Utils {
   public static String foo() {
      return "foo";
   }
}

and a class Service

package pl.jcubic;

public class Service {
   public String test() {
     return Utils.foo();
   }
}

both files have name the same as class, they are in directory ./pl/jcubic/ and when I compile Service I've got an error error: cannot find symbol in line where Utils is.

I've try

import Utils;

got 2 errors error: '.' expected and error: ';' expected in the same line

I've try

import pl.jcubic.Utils;

got error: cannot find symbol in line where import is and in the line where I use the class.

2

There are 2 answers

0
jcubic On BEST ANSWER

OK, I found the solution. I've compile using cd

cd pl/jcubic; javac  Service.java

but it don't work. But it work when I compile

$ javac pl/jcubic/Serive.java
2
SLaks On

You don't need to (and cannot).

Classes in the current package are implicitly in scope.

If you get an error, make sure that the other class has been compiled.