I have two classes that I am compiling from command line.

One is Vehicle class,

class Vehicle{
    int passangers;
    int fuelcap;
    int mpg;
}

and another is VehicleDemo class. This class instantiate an object of Vehicle class.

class VehicleDemo{
    public static void main(String args[]){
        Vehicle minivan = new Vehicle();
        int range;

        minivan.passangers = 100;
        minivan.fuelcap = 16;
        minivan.mpg = 21;

        range = minivan.fuelcap * minivan.mpg;
        System.out.println("Minivan can carry " + minivan.passangers + " with a range of " + range);
    }
}

Since they are in two seperate files I thought I'd have to compile them seperately. But, when I complie VehicleDemo.java it automatically complies Vehicle.java too.

How does java do it? Why it just doesn't raise a flag saying it can't find vehicle class.

Recommended Answers

All 6 Replies

Java does an automatic compilation process where any dependent classes it finds referred to within the class it is compiling are compiled too.
This is nested so if your Vehicle class referred to another class, the .java of which was in the same directory, it would also be compiled when you typed
javac VehicleDemo.java

So, as long as they are in the same directory and they are referenced is some way, java will automatically compile them?

and since those classes are in the same directory, they are in the same namespace, and I don't have to use import to use them?

^ ... provided they are declared as being in the same package. If you use (multiple) packages then you need a directory hierarchy that matches the package hierarchy.

ps: It really has to work that way, just consider two classes each of which references the other.

As long as all the sources you need to compile the application are on the source path for the compiler it will compile them all into the output path (granted that any other classes needed are on the classpath for the compiler and there are no compiler errors generated of course).

You may have multiple source directories just like you may have multiple locations on the classpath, which can be handy when compiling a system comprised of multiple modules (though it's better to compile each module separate).

Thanks guys. These cleared things up.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.