-2

我是Java的新手。我已经完成了一个查找矩形面积的示例程序。代码如下。

package rectangle;

public class Rectangle {
    int length, width;

    int rectArea() {
        int area = length * width;
        return (area);
    }
}

class RectArea {
    public static void main(String[] args) {
        int area1;

        Rectangle rect1 = new Rectangle();

        rect.length = 14;
        rect.width = 13;
        area1 = rect.rectArea();

        System.out.println("Area1=" + area1);
    }
}

在上面的代码中lengthwidth是在类中声明的变量Rectangle。现在area也是一个保存数据的变量length * width,这个area变量也在类中声明Rectangle

我们可以从另一个使用点运算符命名的类中访问length和变量。但是为什么我们不能直接从类(使用点运算符)访问在类中声明的变量来评估 的值? widthRectAreaareaRectangleRectAreaRectangle

也就是说,为什么我们不能使用下面的代码来评估类中新创建的对象的rect1RectArea

area1 = rect1.area;
System.out.println("Area1="+ area1);

或者为什么我们不能使用上面的代码从类中访问area在类中声明的变量?RectangleRectArea

4

4 回答 4

3

area 不是类级别的变量。它是 rectArea 方法中的一个局部变量,因此,它在方法之外是不可见的,并且不能像类变量一样通过点运算符访问

于 2018-01-24T11:29:16.360 回答
1

area不是类变量,它在方法内部,您不能访问方法变量,因为它们是本地的并且仅对方法可见。

于 2018-01-24T11:29:59.030 回答
1

有局部变量和实例(类)变量。类变量就像长度和宽度,它们可以在整个类中使用。

但是对于局部变量,它们只能在您声明它们的方法/代码块中使用。在这种情况下,区域在方法中声明并且仅在方法中可用。

一旦代码跳出方法(return)区域就不再存在了。

我已经修复了下面的代码,以便它可以工作:

    int length, width, area;

        void getData(int x, int y)
        {
            length=x;
            width=y;
        }

        int rectArea()
        {
            area=length*width;
            return area;

        }

        }
        class RectArea{

            public static void main(String[] args) {

                int area1, area2;

                 Rectangle  rect1 =new Rectangle();

                 Rectangle rect2 =new Rectangle();

                rect1.length=14;
                rect1.width=13;
                area1=rect1.length*rect1.width;
                rect2.getData(13,14);
                area2=rect2.rectArea();

          System.out.println("Area1="+ area1);
          System.out.println("Area1="+ area2);
System.out.println("Area1="+ rect2.area);
            }

        }
于 2018-01-24T11:32:26.403 回答
0

area是方法rectArea的局部变量。它在类外甚至类内都无法访问,除了相同的方法。

如果您希望区域可以在外面访问,为什么不尝试这样的事情:

public class Rectangle {

    int length, width, area;

    void getData(int x, int y) {
        length = x;
        width = y;
        area = length * width;
    }
}
于 2018-01-24T11:30:21.010 回答