Page 122 - 2617_JSSPS_C-7
P. 122

For example:

              1  class rectangle
              2  {

              3      int length,breadth,area, perimeter;
              4      rectangle()
              5      {

              6          length=5;
              7          breadth=2;
              8      }

              9      void cal()
              10      {
              11          area = length * breadth;

              12          perimeter = 2*(length+breadth);
              13      }

              14      void display ()
              15      {      System.out.println("Area of Rectangle: " + area);
              16          System.out.println("Perimeter of Rectangle: " + perimeter);

              17      }
              18

              19      public static void main(String[] args)

              20      {
              21          rectangle ob = new rectangle();
              22          ob.cal();

              23          ob.display();
              24      }

              25  }
              Copy Constructor

              The copy constructor is a special type of constructor that is used to create an object by initializing it
              with previously created object of the same class. Thus, in one word it duplicates an object. The different
              ways to initialize the instance variables of one object into another in Java are as follows:

                  By using a constructor
                  By assigning the values of one object into another

              By Using a Constructor

              Here, since object is passed as a parameter, instance variables of the object are copied to the instance
              variable of the current object.







                        Premium Edition-VII
                120
   117   118   119   120   121   122   123   124   125   126   127