Thanks to stackoverflow i finally understood that i need to compile from the source directory when m trying to compile a file which has a object of another class of the same package declared in one of its method. ex-
package p1;
public class accesslevel
{
int n=2;
private int pri_n=3;
protected int pro_n=4;
public int pub_n=5;
public accesslevel()
{
System.out.print("\nin accesslevel constructor");
System.out.print("\nn="+n);
System.out.print("\nprivate n="+pri_n);
System.out.print("\nprotected n="+pro_n);
System.out.print("\npublic n="+pub_n);
}
}
package p1;
class samepckp1test
{
public static void main(String args[])
{
accesslevel a=new accesslevel();
}
}
But i dont get why i need to do that?Can someone help me understand why i need to move one level up?
Because packages in Java are mapped to directories.
So, if you have a
p1directory for yoursamepckp1testclass like this:Then java expects you to be on
p1‘s parent directory to compile to compilep1package. (p1package containssamepckp1testandaccesslevelclasses).If you want your classes to be in the default package (no package declaration at all which I don’t recommend) you can compile them from their container directory (instead of the parent directory in your example).
Rule is: classes are expected to be found inside directories following their package declaration.
That is, if your class
MyClassis incom.stackoverflow.testpackage, your class source is expected to be found in:So you need to be in directory containing the
comsubdirectory.