Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Forward declarations of classes in namespaces

How do I do forward declarations in Java?

I have two classes, each needs to call a method in the other and they both reside within different namespaces. For example...

package one;

class A {
    public void foo() {
        B b = new B();
        b.bah();
    }
}

and

package two;

class B {
    public void bah() {
        A a = new A();
        a.foo();
    }
}

UPDATE

In Eclipse when this code is encountered a compile time error would be thrown up "A cycle was detected in the build path...".

like image 210
Ben L Avatar asked Nov 02 '25 06:11

Ben L


2 Answers

Just import them. Java is a lot cleverer than C++ about these things.

like image 164
Paul Tomblin Avatar answered Nov 03 '25 21:11

Paul Tomblin


In Eclipse when this code is encountered a compile time error would be thrown up "A cycle was detected in the build path...".

I think that Eclipse is complaining because you have a circular dependency between classes in different Eclipse projects in your workspace. Eclipse wants to be able to build projects in a linear sequence.

If you put the mutually dependent classes into the same project, Eclipse would be happy.

like image 20
Stephen C Avatar answered Nov 03 '25 21:11

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!