0

Thanks for help in advance. I am a beginner of Java. I am using a class and defines its constructors. The 1st version is wrong with comments inside the code:

public class QueueByStacks {
    // constructor
    public QueueByStacks() {
        LinkedList<Integer> in = new LinkedList<Integer>();
        LinkedList<Integer> out = new LinkedList<Integer>();
    }

    public Integer poll() {
        move();
        return isEmpty()? null : out.pollFirst();
        // out can not be resolved. But I think out is defined in the constructor then when I call the constructor in the main function then it should be initialized, so why I can not use out here?
    }
}

I modified the code and it works:

public class QueueByStacks {    
    private LinkedList<Integer> in;
    private LinkedList<Integer> out;
    // constructor
    public QueueByStacks() {
        in = new LinkedList<Integer>();
        out = new LinkedList<Integer>();
    }
}

So I am wondering why the 1st version is wrong? My understanding is that when I call a class actually I am calling the constructor so "in" and "out" should be able to be used across the methods. I appreciate any helps. Thanks.

1
  • the 1st version, in/out are local variable, and its lifecycle is just in constructor method. Commented Dec 29, 2016 at 2:17

1 Answer 1

1

I think I found the right post to answer my question. In summary, in my 1st version, "in" and "out" are local variable and they only exist during the execution of constructor.

using a variable in constructor in a method outside of constructor

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.