我可以从Java中的class B访问在class A中声明的变量吗

Can I accessing variables which is declare in say class A from say class B in Java

我是 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是在classRectangle中声明的变量。现在 area 也是一个保存数据 length * width 的变量并且这个 area 变量也在 class Rectangle

中声明

我们可以使用点运算符从另一个名为 RectArea 的 class 访问 lengthwidth 变量。但是为什么我们不能从RectArea class(使用点运算符)直接访问在Rectangle class中声明的area变量来计算值Rectangle

也就是说,为什么我们不能使用下面的代码来评估 RectArea class.

中新创建的对象 rect1 的值
area1 = rect1.area;
System.out.println("Area1="+ area1);

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

area 不是 class 级变量。它是 rectArea 方法中的一个局部变量,因此,它在方法外部不可见,也不能通过点运算符访问,例如 class variables

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

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

如果你想让 area 可以在外面访问,你为什么不尝试这样的事情:

public class Rectangle {

    int length, width, area;

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

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

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

一旦代码跳出方法(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);
            }

        }