javaclassvariablesdot-operator

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


I am a newbie in Java. I have done a sample program that is finding the area of a rectangle. The code is below.

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);
    }
}

In the above code length and width are variables which declare in class Rectangle. Now area is also a variable which holds the data length * width and this areavariable is also declared in class Rectangle

We can access length and width variables from another class named RectArea by using the dot operator. But why can't we access area variable which is declared in Rectangle class from the RectArea class (using dot operator) directly to evaluate the value of Rectangle?

That is, why we can't use the below code to evaluate the value of a newly created object rect1 from RectArea class.

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

Or why can't we access the area variable which is declared in Rectangle class from RectArea class using the above code?


Solution

  • area is not the class level variable. Its a local variable in rectArea method, thus, it will not be visible outside the method and won't be accessible via dot operator like class variables