[3907] in java-interest
Re: Mutually-referential classes ?
daemon@ATHENA.MIT.EDU (Per Danvind)
Fri Dec 1 14:34:15 1995
To: Bob Beck <rbk@ibeam.jf.intel.com>
cc: java-interest@java.sun.com
In-reply-to: Your message of "Thu, 30 Nov 1995 12:52:00 PST."
<m0tLFyG-000RXhC@ibeam.intel.com>
Date: Fri, 01 Dec 1995 16:39:42 +0100
From: Per Danvind <perry@cdt.luth.se>
Hi Bob...
> I saw some words on this in older postings, but no answer, so I'll ask again...
>
> Suppose I have two classes that refer to each other (eg, ClassA and ClassB;
> ClassA has a ClassB instance variable and invokes methods in that instance;
> ClassB has methods that take ClassA arguments). Both need to be public
> classes (so they can be inherited from in different packages). Can this be
> done in Java? The rules seem to be that public classes must be contained in
> separate .java files; however, you can't import a class before it's compiled
> and each class needs the other to be compiled first. Is there some way
> around this?
>
> This is easy (and not uncommon) in C++ code, and it works fine in Smalltalk ...
> --
> Bob Beck rbk@ibeam.intel.com CompuServe: 71674,106
> Intel Corporation (503)264-8856 AOL: RDBeck
It is very easy in Java too. Have you tried it?
This simple program should do what you want...
public class ABTest {
public static void main(String args[]) {
A a = new A("Joe");
a.print();
}
}
public class A {
B b;
public String name;
public A(String str) {
this.name = new String(str);
this.b = new B("Child of "+str);
}
public void print() {
System.out.println("Entering print in A...");
System.out.println("This is '"+this.name+"'.");
b.print(this);
System.out.println("... exiting print in A.");
}
}
public class B {
String name;
public B(String str) {
this.name = new String(str);
}
public void print(A a) {
System.out.println("Entering print in B...");
System.out.println("My owner is '"+a.name+"'.");
System.out.println("... exiting print in B.");
}
}
--
Per
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com