fly_over_32
fly_over_32

Reputation: 79

how to compile java with multiple files using command line

I am pretty new to Java and Linux. I can't use an IDE but i have jdk installed (obviously). I have three .java files that i want to compile. One is the main code file and two small classes. how do i compile them using terminal? these files are called:

  • main.java
  • object.java (Object.class when compiled)
  • living.java (Living.class when compiled)

object.java and living.java only have a constructor for now that i want to call

i've tried

javac main.java #this seems to be the right one
javac main.java object.java living.java
javac main.java Object.class Living.class

in terminal and

import object.java;
import living.java;

import Object.class;
import Living.class;

import object;
import living;

import Object;
import Living;

in the main.java file

but nothing seems to work

when i use

import Living;

in the code it tells me that it misses a ; or .

, when using precompiled

import Living.class

in the code i get

error: class, interface, or enum expected
import <Object.class>;

in the terminal and when i try

import living.java

in the code i get

error: package living does not exist
import living.java;

in terminal

so what am i doing wrong? do i have to import precompiled classes or java codefiles? do i have to tell javac all files i want to use or only the main.java file? main.java compiles without error when i don't try to import one of the classes. And if i have to use .jar files please explain and give an example

Upvotes: 0

Views: 885

Answers (2)

SirFartALot
SirFartALot

Reputation: 1225

Your file name has to match the class name, e.g. if you have a class Living {... your file name has to be named Living.java. Be aware of the same character casing here. If you use package xyz; in Living.java, you also have to place your file in the subdirectory xyz (e.g. xyz/Living.java).

Importing is to be done by import Living;, with the same case. On using package xyz; in your Living.java, you have to use import xyz.Living;. Classes within the same package doesn't need to be imported.

You compile your files by using javac Living.java or with package javac xyz/Living.java. The javac will produce the Living.class/xyz/Living.class file.

Same with Main.java.

To run a classes main method, you have to run the java executable with the class name, which contains the static void main(...) method, e.g. java Main (or java xyz.Main if Main has a package xyz;).

Never create an Object.java, since Object is already reserved...

BTW: maybe you follow one of the many tutorials available online, to get a first glance on java...

Upvotes: 1

fly_over_32
fly_over_32

Reputation: 79

as @Arnaud commented: "Note that if all three classes are in the same package, you don't need to import them in your code"

i don't need to import these classes in this case and leaving import away works.

Upvotes: 0

Related Questions