class outer
{
private String s = "test1";//这里
void ff()
{
String s = "test2";//如果写上这行,那么下面一句打印就是打印s这个局部变量。如果没有这行那么打印成员变量。 去了解下变量的作用域
System.out.println(s);
}
}
class test 
{
public static void main(String[] args) 
{
new outer().ff();
}
}

解决方案 »

  1.   

    String s = "test2"; //这是局部变量,如果和上面的成员变量重名,会在这个局部变量的范围内覆盖掉成本变量;
      

  2.   

    恩,都是正解,变量的作用域是就近原则。如果,特殊指定可以用关键字,this ,super之类的。看看基础的 doc ,api  吧
      

  3.   

    class outer {
    String s = "test1";
    String ff() {
    String s = "test2";
    return s;
    }
    }class Test {
    public static void main(String[] args) {
    outer out=new outer();
    System.out.println(out.ff());
    System.out.println(out.s);
    }
    }
    输出:
    test2
    test1自己想吧
      

  4.   

    class outer
    {
    private String s = "test1";//此处s为outer的属性(变量),是成员变量;

    void ff()//此处为outer的方法
    {
    String s = "test2";//此处的s是定义在ff()方法里的局部变量
    System.out.println(s);//如果s前面没有指明是谁的变量,那么默认指的是最近一次定义的s,显然是最近定义的局部变量s;
    System.out.println(this.s);//如果需要调用成员变量s,那么前面需要写上this,this是指向该对象本事.
    }
    }class test 
    {
    public static void main(String[] args) 
    {
    new outer().ff();
    }
    }