如果我为方法内的变量赋值,它是否会超出该方法的范围?

时间:2018-02-15 11:26:02

标签: java

很抱歉,如果这是重复,我已经尝试寻找我的问题的答案,但无法找到我之后的答案。

我是Java的新手(字面意思是昨天开始),我试图理解为什么如果我在我的类中声明一个变量然后在 void 方法中为其赋值,与该变量关联的值仍然超出方法的范围。我(非常)有限的方法理解是它们有自己的范围,我认为访问方法中所做的任何变量的唯一方法是在方法结束时返回它们。情况不是这样吗?

3 个答案:

答案 0 :(得分:0)

答案有点复杂。

首先开始区分方法功能

一个方法通过调用类的构造函数(例如MyClass obj = new MyClass();)来实例化对象。从这一点开始,您的对象具有状态,由成员变量表示(所有不是 strong>在您的课程中声明static。 方法(作为对象的一部分)可能会更改此状态(除非声明相应的变量为final)。

为了能够这样做,一个方法继承了该类的范围,但是变量被绑定到对象的实例,在该对象上调用该方法。

例如:

public class MyClass {
    private int a = 0;
    public void aplusplus() {a++;}
}

MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.aplusplus();  // the a of obj1 is now 1
obj2.aplusplus();  // the a of obj2 is now 1
obj1.aplusplus();  // the a of obj1 is now 2

但要注意!还有一个名为隐藏的概念。 如果在方法体内声明局部变量,则隐藏类成员变量。按名称访问变量会导致访问局部变量,而不是成员变量。在为私有成员实现setter方法时,这尤其有趣,通常方法的参数(它是一个局部变量)被命名为成员变量。要仍然访问成员变量,您可以使用this.variablename。例如:

public class MyClass {
    private int a = 0;
    public void aplusplus() {a++;}
    public void setA(int a) {this.a = a;}
}

答案 1 :(得分:0)

类中的每个方法都将继承任何属性(变量)或任何直接属于该类的方法。说

public class Bicycle {

    public int gear;
    public int speed;

    // the Bicycle class has
    // two  methods

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void speedUp(int increment) {
        speed += increment;
    }
}

让我们得到setGear方法

public void setGear(int newValue) {
    gear = newValue;
}

如您所见,我可以访问'gear'属性,因为它属于Bicycle类。参数'(int newValue)'仅属于此方法,这意味着我只能在此方法中访问此变量,如下所示:

public void setGear(int newValue) {
    newValue = gear;
    //this wouldn't make much sense logic wise, but it is
    //valid code since I can use newValue only inside the setGear method

    speedUp(10);
    //the method 'speedUp' belongs to the bicycle class, so I can use
    //it inside another method belonging to the same class
}

或者,我可以使用this关键字来表示我引用的是类属性,如下所示:

public void setGear(int gear) {
    this.gear = gear;
    //I am telling the method that the class attribute 'gear' will 
    //receive my parameter value 'gear'
    //this is useful when my parameter variable name has the same 
    //name as my class attribute
}

编辑:忘了赞扬官方oracle文档https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html

答案 2 :(得分:0)

您在问题中说明您已在中声明了一个变量。这意味着变量设置为的任何值(在方法调用期间)将持续跨方法调用。变量是对象的一部分,因此称为实例变量

如果在方法定义中声明变量,它们就在方法的范围内。它们是 this.yourMethod()的一部分。据说这些变量是该方法的局部变量。您只能在方法中使用这些变量。 对象不知道它们存在。