tumba25
tumba25

Reputation: 464

Declare two classes from eachother

I'm writing a app in NetBeans. I have two classes MyApp_View and MyApp_Functions.

The MyApp_View class starts like this

public class MyApp_View extends FrameView {
MyApp_Functions My_functions = new MyApp_Functions();

public MyApp_View(SingleFrameApplication app) {
    super(app);

In MyApp_Functions I have
MyApp_View my_view = new MyApp_View(null);

I want to access the public variables in MyApp_View from MyApp_Functions and the public methods in functions from view, but have no success with this.

Is this doable? And how?

Edit: Judging by the answer I got I think it's best to clarify.

If I declare MyApp_View in MyApp_Functions or MyApp_Functions in MyApp_View, it works as expected. But I can't access public stuff in both classes from the other. I can obviously only access things from the one I declared.

If I try to declare MyApp_View in MyApp_Functions and MyApp_Functions in MyApp_View they compile fine. But I get a null exception error on start.

Again. Easier to understand? Is this doable? And how?

Upvotes: 0

Views: 1311

Answers (3)

Kevin K
Kevin K

Reputation: 9584

MyApp_View my_view = new MyApp_View(null);

This creates a new MyApp_View object, which is not the same as the one that constructed the MyApp_Function. It sounds like what you want is to have the two objects have references to each other. I usually set that up using a parameter in the constructor for one of the objects. Here's an example:

class A {
    private B b;

    public A() {
        this.b = new B(this);
    }
}

class B {
    private A a;

    public B(A a) {
        this.a = a;
    }
}

Now objects of type A can access the associated object B through A.b, and the object B can access the associated object A through B.a. In your example, A is MyApp_View, and B is MyApp_Functions.

Upvotes: 1

CurtainDog
CurtainDog

Reputation: 3205

You need to pass a reference from one to the other. At its most basic it would invlove changing your second line to:

MyApp_Functions My_functions = new MyApp_Functions(this);

and adding the appropriate constructor to MyApp_functions that 'saves' the reference in a variable, which can then be used whenever you need to access something from MyApp_View.

Ultimately though, you want to ask if such relationships are really necessary and perhaps re-architect the system to remove them.

Upvotes: 2

Etaoin
Etaoin

Reputation: 8724

Accessing the public members is easy -- for example, just using My_functions.foo will access the public foo variable on your object My_functions of the MyApp_Functions class, and likewise using my_view.bar() will call the public bar() method on that object.

I suspect, though, that your problem is a more general one with object-oriented thinking; I recommend picking up an introductory Java book and working through it -- there's really no substitute for a good solid grounding in the way OO programmers think.

Upvotes: 0

Related Questions