Nightfortress
Nightfortress

Reputation: 43

Java different instances of a class

For simplicity sake I have replicated the error I am experiencing with the key elements causing the problem.

I have three main classes, the first is the main class which initialises and sets up methods (main). Then I have a database class which pulls data from a database into the code (Init). Thirdly I have a GUI class which handles the GUI elements (accessor).

I have encountered a problem where a variable (message) that I have initialised in the database class (accessor.setUp) from the main class (init.setUp) is appearing as null when I call the accessor.print() method from the GUI class after an ActionListenerEvent.

I get that this is happening because there are different instances of the same class but I am not sure how to solve it.

This is the main class:

public class main {
    public static void main(String[] args){
        Init init=new Init();
        init.setUp();

        Accessor acc=new Accessor();
        acc.tryAccess();
    }
}

This is the init class:

public class Init {
    public String message;

    public void setUp(){
        message="Hello World";
    }
    public void print(){
         System.out.println(message.length());
    }
}

This is the accessor class:

public class Accessor {
    public void tryAccess(){
        Init init=new Init();
        init.print();
    }
}

Thanks in advance.

Upvotes: 0

Views: 72

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You have too many Init objects, and the one is not related to the other. It should be obvious that setting up one will have no effect on the other, and to solve this, you just need and want one instance. Change

public class main {
    public static void main(String[] args){
        Init init=new Init();
        init.setUp();

        Accessor acc=new Accessor();
        acc.tryAccess();
    }
}

to

public class main {
    public static void main(String[] args){
        Init init=new Init();
        init.setUp();

        Accessor acc=new Accessor(init);  // pass it in!
        acc.tryAccess();
    }
}

and then pass the parameter Init object into the init field in the Accessor object.

public class Accessor {
    private Init init;

    public Accessor(Init init) {
        this.init = init;  // initialize field
    }

    public void tryAccess(){
        // Init init=new Init();  // *** don't create a new instance!! ***
        init.print();
    }
}

Upvotes: 2

Related Questions