views:

158

answers:

4

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...".

+5  A: 

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

Paul Tomblin
The order of imports is not important in Java. Cyclic references are possible without any extra code.
Morgaelyn
A: 

Well, you import the classes:

package one;

import two.B;

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

or use their full name:

package one;

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

But, needless to say, that will cause an exception to be thrown (at least, in the snippet you posted...).

Bart Kiers
my snippet is crap I know, but it gets the point across! ;)
Ben L
@Ben, yeah, I thought you knew, but wanted to mention it to be sure.
Bart Kiers
A: 

Given the comments here (ie you don't need to do explicit forward declarations as the compiler can cope) I have downgraded the Eclipse error to a warning and will have to just ignore it.

To do this go to...

Window > Preferences > Java > Compiler > Building > Build path problems > Circular dependences

Ben L
Surely Eclipse is warning you that you will get a StackOverflowError if you run this code? Or does your real code have some sort of break out condition that will stop the continuous cycle?
DaveJohnston
this isn't 'real code', it's just an example of some code that describes my problem.
Ben L
+1  A: 

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.

Stephen C