What is the difference between a member variable and a local variable?

前端 未结 7 773
再見小時候
再見小時候 2020-11-29 08:01

What is the difference between a member variable and a local variable?

Are they the same?

7条回答
  •  渐次进展
    2020-11-29 08:44

    There are two kinds of member variable: instance and static.

    An instance variable lasts as long as the instance of the class. There will be one copy of it per instance.

    A static variable lasts as long as the class. There is one copy of it for the entire class.

    A local variable is declared in a method and only lasts until the method returns:

    public class Example {
        private int _instanceVariable = 1;
        private static int _staticvariable = 2;
    
        public void Method() {
            int localVariable = 3;
        }
    }
    
    // Somewhere else
    
    Example e = new Example();
    // e._instanceVariable will be 1
    // e._staticVariable will be 2
    // localVariable does not exist
    
    e.Method(); // While executing, localVariable exists
                // Afterwards, it's gone
    

提交回复
热议问题