tags:

views:

58

answers:

3

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?

A: 

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.

Etaoin
Personal recommendation: "Head First Java" by Kathy Sierra and Bert Bates
Dolph
for OO, I would rather suggest some SmallTalk or Ruby book:))
Gabriel Ščerbák
+2  A: 

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.

CurtainDog
+1  A: 

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.

Kevin K