TDH
TDH

Reputation: 25

Help me understand how variables work in Java

I am having problems understanding how private and public variables work. I am trying to fill the myStorage.outString variable from myThread. But it seems I cannot see the setInString method from myThread. Here is my example:

public class CT63_Console extends MIDlet {
    public Storage myStorage;
    public void startApp() {
        this.myStorage = new Storage();
    }
}

public class storage{
    private String[] outString;

    public Storage(){
        AClass myThread = new AClass();
        myThread.start();
    }
    public void setInString(String sendString){
        this.outString = sendString; //push seems not to be supported by MIDP
    }
}

public class AClass{
    public void run(){
        myFunction("write this into Storage var outString");
    }

    private myFunction(myString){
        myStorage.setInString(myString);
    }
}

What do I have to do to set the variable and why am I wrong?

Upvotes: 1

Views: 349

Answers (2)

Iñigo Beitia
Iñigo Beitia

Reputation: 6353

You are trying to access myStorage without having a reference to it. You could pass this reference when you create the AClass instance.

Also, you are trying to assign a String to an array of Strings which can't be done.

public class Storage{
    private String outString;

    public Storage(){
        AClass myThread = new AClass(this);
        myThread.start();
    }
    public void setInString(String sendString){
        this.outString = sendString; //push seems not to be supported by MIDP
    }
}

public class AClass {
    Storage myStorage;

    public AClass(Storage s) {
        this.myStorage = s;
    }

    public void run(){
        myFunction("write this into Storage var outString");
    }

    private myFunction(String myString) {
        myStorage.setInString(myString);
    }
}

Upvotes: 1

poke
poke

Reputation: 388313

this.outString = sendString;

outString is an array of strings (String[]). You cannot assign a single string to an array of strings. So either you need to change the type of that variable to a single string (just String), or you need to specify an index where you assign that string to. Note that in the latter case you need to initialize the array first.

Upvotes: 0

Related Questions