Rui
Rui

Reputation: 131

Eclipse: Inherit Java classes on another project

first of all here's the warning that I'm fairly a newbie on Eclispse and Java. And am currently working on a school assignment.

So, I initially created a Project P1 where I implemented class A. Notice that I didn't define any package. So it's all on the default package, on all classes.

Then I've created a new project P2 where I implement class B. Class B inherits from A like:

public class B extends A {

In order to be able to use the class on the new project I've edited project like: Java Build Path -> Add Class Folder and add the location of class A's source. All built and ran well.

Then I've created a new project P3 where I implement class C. Class C inherits from B like:

public class C extends B {

Again I've edited project like: Java Build Path -> Add Class Folder and add the locations of class A's and class B's source. However now I get an error. I get an error that i can't find class A. The error I see on the first line already, under 'B'.

I'm probably doing something wrong, as this way of adding dependencies doesn't seem to make sense. Adding all classes on the inheritance tree seems nonsensical. Can someone explain what I'm doing wrong (probably more than 1 thing).

Regards, Rui

Upvotes: 0

Views: 1721

Answers (1)

cello
cello

Reputation: 5486

If you want to use the sources from one project in another project in Eclipse, do not just add a class folder. Instead, define a dependency on the other project.

To define that project P2 should use the sources/classes of project P1, open the project settings of P2, and go to "Java Build Path". Instead of adding a source folder, switch to the "Projects" tab. Click on "Add…" and select your project P1.

Next, switch to the tab "Order and Export" and make sure that the project P1 is marked as being exported. This ensures that if you add a dependency from P3 to P2, P3 will also get the sources from P1.

Note that this setup will only work in Eclipse. For larger systems, a dependency management system like Maven or Gradle should be used which standardizes the definition and setup of such dependencies and handles them in a way that it works across different IDEs and build systems.

Upvotes: 1

Related Questions