简体   繁体   English

Java变量范围

[英]Java variable scope

当一个变量初始化无论是在本地范围内以及全球范围内,我们如何利用全球范围内不使用this在同级别的关键字?

class MyClass{
    int i;//1
    public void myMethod(){
        i = 10;//referring to 1    
    }

    public void myMethod(int i){//2
        i = 10;//referring to 2
        this.i = 10 //refering to 1    
    }    
}  

Also See : 另请参阅:

如果不使用this它将始终是局部变量。

It is impossible without this. 没有这个是不可能的。 The phenomenon is called variable hiding . 这种现象称为变量隐藏

If you are scoping the variable reference with this it will always point to the instance variable. 如果您要在this范围内定义变量引用,它将始终指向实例变量。

If a method declares a local variable that has the same name as a class-level variable, the former will 'shadow' the latter. 如果方法声明的局部变量与类级变量的名称相同,则前者将“遮盖”后者。 To access the class-level variable from inside the method body, use the this keyword. 要从方法主体内部访问类级变量,请使用this关键字。

public class VariableScope {

    int i=12;// Global
    public VariableScope(int i){// local

        System.out.println("local :"+i);
        System.out.println("Global :"+getGlobal());
    }
    public int getGlobal(){
        return i;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM