sanjay patil
sanjay patil

Reputation: 13

import class/package placed in another package of same/higher level of hierarchy

I have two folders pack1 and pack2 in my desktop. pack1 contains file1.java file and the code is:

public class File1 {
    public static void main(String[] args){     
    }   
}

and pack2 contains file2.java and the code is:

import pack1.File1;
public class File2 {
    public static void main(String[] args){     
    }   
}

I successfully compiled file1.java and file1.class is created in pack1 but I got error while compiling file2.java:

error: package pack1 does not exist
import pack1.File1;
            ^
1 error

from the above error what I thought is I can only import class/package which are present in same or sub-directories because Pack1 is not in the same directory in which I am compiling(current working directory = $HOME/Desktop/pack2) please correct me if I am wrong.

If my understanding is correct how can I import file1 in file2.

Upvotes: 0

Views: 1573

Answers (1)

GhostCat
GhostCat

Reputation: 140417

You have to understand:

  • "the real" class name is always the.complete.package.WhateverClass
  • there is no concept of "sub packages".

Sure, from a directory perspective the classes for a.b and a.c will all sit in folders within the a directory, but for anything inside a.b, it still has to use the full name a.c.Whatever

Thus your import always look the same, like:

import com.pack1.subpack2.TheClass

In other words: when your code sits in a.b, there is no difference in importing from a.c or x.y.z, you simply always give the full class name, with all the packages that belong to it.

Upvotes: 3

Related Questions