简体   繁体   中英

How do I solve this package error in Java?

I want to create a custom package in Java, lets call it package alphabets. And I have two separate classes, class A and class B. I want to add class A in package alphabets and import it in class B.

Here is code for class A

package alphabets;

public class A
{
    public void printHello()
    {
        System.out.println("\n 
        Hello! I am from class 
        A\n");
    }
}   



Here is code for class B

import alphabets.*;

public class B
{
    public static void main(String 
     args[])
    {
        A obj = new A();
        obj.printHello();
    }
}

Then I compiled class A using the following in terminal:
javac -d. A.class
After doing this I get a folder alphabets which contains A.class file
Then I compile class B using:
javac B.java

The problem is after compiling class BI get an error unable to access A , but when I put the A.java( source file ) into the alphabets folder( which contains just A.class file ), then it compiled successfully.

My question is why I got the error in first place and how did it resolved when I put A.java file in alphabets folder.

Does the A.class file and A.java file need to be in same folder. So class B can access it or is there another reason.

You shouldn't need to compile java files into class files. Just use an IDE like Eclipse it'll be a lot easier.

As for why things were fixed when you put the files named "A" in the "alphabets" folder, it's because you imported them in. The java and class file do need to be in the same folder because you're not using an IDE.

No they don't (I just edited the earlier post.) What I had previously meant was that all of the class files need to be in the same location relative to each other, as do the java files, but the class and java files do not need to be in the same folder. In the previous line where I say relative to each other, I mean that, for example, if A.java is in the package alphabets and B.java is in the default folder (as you seem to have,) A.class will need to be in an alphabets folder and B.class will need to be in a "default" folder (although I would just make another package folder for the B.class/B.java. Also the packages will need to be in the same folder overall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM