Java: Accessing object members

This entry is part 22 of 54 in the series Learn Java

In addition to creating the object, the members of the class that are to be accessible beyond their package need to be declared as public in the class definition.

The members of this object can now be reached by using the dot operator after the instance name.

In this example, the members of the object MyRectangle are x, y and getArea().

package javaapplication19;

public class JavaApplication19 {

    static class MyRectangle {
        public int x, y;
        
        public int getArea() {
            return x * y;
        }
    }

    public static void main(String[] args) {
        MyRectangle r = new MyRectangle();      
        r.x=10;
        r.y=5;
        int area = r.getArea();
        System.out.println(area);      
    }
}

 

 

 

Series Navigation<< Java: Object creation
Java: Constructor >>

Leave a comment

Leave a Reply