区别一:定义的位置不同
定义在类中的变量是成员变量
定义在方法中或者{}语句里面的变量是局部变量
区别二:在内存中的位置不同
成员变量存储在堆内存的对象中
局部变量存储在栈内存的方法中
区别三:生命周期不同
成员变量随着对象的出现而出现在堆中,随着对象的消失而从堆中消失(gc垃圾回收机制)
局部变量随着方法的运行而出现在栈中,随着方法的弹栈而消失
区别四:初始化不同
成员变量因为在堆内存中,所有默认的初始化值
局部变量没有默认的初始化值,必须手动的给其赋值才可以使用。
package com.oracle.demo02; public class Animal { private String color; private int leg; // 变量就近原则 public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getLeg() { return leg; } public void setLeg(int leg) { this.leg = leg; } }