In this Java Example we declares a class named Rect. It contains two integer member variables, l and b (for length and breadth). Since no access specifier is used, these variables are considered public. Public means that any other class can freely access these two members.
We create an object by name rect of class Rect by instantiating the class. When we create a new object, space is allocated for that object and for its member’s l and b. Then the values are assigned to l and b variables as 20 and 60 respectively. After this, the variables l and b of object rect are multiplied and the result is stored in variable a which is then displayed on the screen.
class Rect
{
int l,b;
}
class CalAreaofRectangle
{
public static void main (String args[])
{
int a;
Rect rect = new Rect();
rect.l=20;
rect.b=60;
a=rect.l*rect.b;
System.out.println("Area of Rectangle is : "+a);
}
}
In previous, Java example, the object rect directly allows to assign values to its data members l and b in main() because both are considered public:
rect.l=20;
rect.b=60;
In the following example, the values of the data members l and b are changed with the help of method: setval()
class Rect
{
int l,b;
void setval(int x,int y)
{
l=x;
b=y;
}
int area()
{
return (l*b);
}
};
class CalculateAreaofRectangle
{
public static void main (String args[])
{
Rect rect = new Rect();
rect.setval (50,8);
System.out.println("Area of Rectangle is : "+rect.area());
}
};
To set the values of the variables l and b, we use this method:
rect.setval(20,10);
This Java statement calls rect’s setval method with two integer parameters 20 and 10 and that method assigns new values to variables l and b respectively.
We append the method name to an object reference with an intervening period (.). Also, we provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, use empty parentheses. Syntax for calling a method through object:
objectReference.methodN ame(argument List);
or
objectReference.methodName();
ObjectReference must be a reference to an object.
Example:
rect.area();
We can use the dot notation to call the area() method to compute the area of the new rectangle.