Java newbie problem: classes of the same package accessing each other?

Classes belong to the same pkg. They are located in a directory named pkg.

  • In general, how can classes access each other in the same pkg?

Error

javac PackTest.java PackTest.java:8: cannot find symbol symbol : class PriTest location: class pacc.PackTest System.out.println(new PriTest().getSaluto()); ^ 1 error 

Classes in PKG pacc

 $ cat PackTest.java package pacc; import java.io.*; public class PackTest { public static void main(String[] args) { System.out.println(new PriTest().getSaluto()); } } $ cat PriTest.java package pacc; public class PriTest { public PriTest(){} private String saluto="SALUTO FROM PriTest"; public String getSaluto(){return saluto;} } 

PKG named dir

 $ find .. -type d -name "pacc" ../pacc $ ls ../pacc makefile PackTest.java PriTest.java $ ls makefile PackTest.java PriTest.java 

Solved!

 $ cat makefile p: javac ./pacc/PackTest.java java pacc/PackTest $ make p javac ./pacc/PackTest.java java pacc/PackTest SALUTO FROM PriTest 
+4
source share
5 answers

MAYBE (So don't kill me, please) this solution:

In the terminal, go to the root of your java project (so by default in your default folder is the parent directory of the pacc folder).
Then enter: javac pacc.PackTest.java

I do not use the compiler manually. My IDE does this for me.

+2
source

Make sure the files are in the same directory with the same name as the package. Also, make sure the classpath is set correctly.

The packages mimic the directory structure - "Test.java" in the package "org.example.test" should be found in "org / example / test / Test.java".

The following files compiled for me:

  $ javac -cp "." *.java 

And I ran with

  $ cd .. $ java pacc.PackTest 

There is no problem.

By the way, Apache Ant is usually preferred over makefiles in the Java universe.

+6
source

If you use the C and C ++ approach to compile each file separately, you may be surprised to learn that the Java compiler works best when you fully compile the entire project .

Apache Ant is a commonly used tool for creating Java projects. It makes a javac call for you. It works better for Java than make(1) does.


Compile as:

 H:\test\so>javac pacc/PackTest.java pacc/PriTest.java 

You must be in the root of your project, not in the pacc folder.

+1
source

Get the ideal of IntelliJ IDEA. Java is so complex and bloated that it will help, so you don’t even have to worry about such trivial things.

0
source

Once you have mastered the basics, the IDE is an important productivity tool.

Until then, it will be helpful for you to think through these issues in order to gain a deeper understanding of Java development.

As for ANT, it’s worth your time to move on to this. Makefiles does not offer you further edification of programming.

0
source

Source: https://habr.com/ru/post/1308666/


All Articles