The best place to *find* answers to programming/development questions, imo, however it's the *worst* place to *ask* questions (if your first question/comment doesn't get any up-rating/response, then u can't ask anymore questions--ridiculously unrealistic), but again, a great reference for *finding* answers.

My Music (Nickleus)

20131125

[SOLVED] "Eclipse: The resource is not on the build path of a java project" - how to use a class in another package

i'm using some time to go back and review some basic concepts in java, so today i read about Controlling Access to Members of a Class.

i set up the following java code package structure in eclipse:
src/
--test/accesscontrol/
----PackagePrivateA.java
----PackagePublicA.java
--test2/
----AccessControlTest.java

Eclipse's "Java EE" perspective:



Eclipse's "Java" perspective:




####PackagePrivate.java####

package test.accesscontrol;

class PackagePrivate {
    PackagePrivate() {
        System.out.println("PackagePrivate() constructor");
    }
}


####PackagePublic.java####

package test.accesscontrol;

public class PackagePublic {
    public PackagePublic() {
        System.out.println("PackagePublic() constructor");
    }
}


####AccessControlTest.java####

package test2;

import test.accesscontrol.PackagePublic;

public class AccessControlTest {
    public AccessControlTest() {
        PackagePrivate pPriv = new PackagePrivate();
        PackagePublic pPub = new PackagePublic();
        System.out.println("AccessControlTest() constructor");
    }
}


####

---
NOTE: the red line in the class AccessControlTest:
PackagePrivate pPriv = new PackagePrivate();

will not work (and is not expected to work) because class PackagePrivate is declared with a package-private access modifier, i.e. no "public" in front of the "class" keyword identifier, so the class AccessControlTest shouldn't have access to the class PackagePrivate because of java's access control rules.
---

however, when i first tried importing/referencing the class PackagePublic in the class AccessControlTest, i got the following error in eclipse:
The resource is not on the build path of a java project

theoretically, it should work fine because the class PackagePublic is declared as a public class, "in which case that class is visible to all classes everywhere" (provided it's visible in the classpath).

i found out that the reason eclipse wasn't finding the class PackagePublic was because the src folder wasn't set as a source folder.

so to fix this:
* change to eclipse's "Java" perspective
* right click on the src folder > Build Path > Use as source folder


No comments:

Post a Comment