Class scope variable vs method scope variable

后端 未结 3 368
独厮守ぢ
独厮守ぢ 2021-01-26 23:59

I know that variable scope is enclosed by a start of block { and an end of block }. If the same variable is declared within the block, then the compile

3条回答
  •  失恋的感觉
    2021-01-27 00:24

    Here is a good example of java scopes (from OCA java SE-7). Here z(class variable) is initialized inside the method, doStuff2. Class variables can be initialized inside the method but if the same variable is re-declared inside a method, a new local variable is created on the stack instead of the heap.

                public class ScopeTest
                {
                int z;
                public static void main(String[] args){
                ScopeTest myScope = new ScopeTest();
                int z = 6;
                System.out.println(z);
                myScope.doStuff();
                System.out.println(z);
                System.out.println(myScope.z);
                }
                void doStuff() {
                int z = 5;
                doStuff2();
                System.out.println(z);
                }
                void doStuff2()
                {
                z = 4;
                }
                }
    

    The output:

    6 
    5 
    6 
    4 
    

提交回复
热议问题