Saturday 2 March 2013

Accessing class members


All variables must be assigned values before they are used in our program.  All class members are accessed by means of “dot” operator.
The general format of accessing instance variable of the class by dot operator is as
            Syntax:            objectname.variablename;
Where, objectname is name of the object, variablename is the name of the instance variable.
            Example:         rect1.length=15;
                                    rect1.width=10;

15
 
 

                                                                                    rect1.length
10
 
            rect1
                                                                                    rect1.width


The general format of accessing instance methods of the class by dot operator is as
            Syntax:            objectname.methodname(parameter-list);
Where, objectname is name of the object, methodname is the name of the instance method that calls with the object and paramerter-list is a list of actual values separated by commas.
            Example:         void getdata(int x, int y)
                                    {
                                                      length=x;
                                                      width=y;
                                    }

                                    rect1.getdata(10,20);

// Write a program to calculate the area of a rectangle.

class Rectangle
{
int length1,width1;
void getdata(int x,int y)
{
length1=x;
width1=y;
}
int calarea()
{
int area=length1*width1;
return area;
            }
}

class prg
{
            public static void main(String[] args)
            {
                        int a,b;
                        Rectangle rect1=new Rectangle();
                        Rectangle rect2=new Rectangle();
                        rect1.length1=15;
                        rect1.width1=4;
                        a=rect1.length1*rect1.width1;
                        System.out.println("Area of Rectangle1="+a);
                        rect2.getdata(2,3);
                        b=rect2.calarea();
                        System.out.println("Area of Rectangle2="+b);
            }
}

No comments:

Post a Comment