2.1. Program
to access variables and methods using objects.
Class
Rectangle
{
Int length, width; // Declaration of variables
Void getdata(int x, int y) // definition
of method
{
Length=x;
Width=y;
}
Int Area( ) // definition of another method
{
Int
area=length*width;
Return(area);
}
}
Class
RectArea // Class with main method
{
Public static void main(String
s[])
{
Int area1,
area2;
Rectangle
obj1=new Rectangle ( ); // creating objects
Rectangle obj2=
new rectangle( );
Obj1.length=5; // accessing variables
Obj1.width=5;
Area2=obj1.length*obj1.width;
Obj2.getdata(10,20); // accessing methods
Area2=obj.area(
);
System.out.println(‘’Area1=”+Area1);
System.out.println(“Area2=”+area2);
}
}
Output is
Area1 = 25
Area2 = 200
0 Comments
Please share your opinions and suggestions with us.