Search This Blog

Saturday, August 20, 2011

What are Constructors ?

जावा में constructors हमेशा क्लास के नाम के ही होते है और उनका पहला अक्षर क्लास की ही तरह बड़ा होता है  | constructors कभी कोई value return नहीं करते है void भी नहीं  | Value return का मतलब जावा में नए लोग शायद समझे नहीं , इसको साधारण तरीके से ऐसे समझा जा सकता है की function में सारी फलावट करने के बाद जो उत्तर आता है उसको return value कहते है |
Constructor को समझने के लिए तीन बाते याद रखना बहुत जरूरी है :

  • यह एक प्रकार का फंक्शन होता है जो क्लास के इंस्टांस को शुरू करने में प्रयोग होता है ।
  • इसका कोई return टाइप नहीं होता 
  • इसको ओवरलोड किया जा सकता है जैसे एक ही नाम के दो या उससे अधिक constructor हो सकते है अलग अलग arguments के साथ 
Constructor अलग अलग तरीके के parameter(जो function के bracket में लिखते है) ले सकता है | नीचे example में,हम दो constructors के बारे में जानेगे |

public class Constructor1 { //public(बहार से access हो सके ) क्लास का declaration जिसका नाम Constructor1 है

int length; // lenght variable integer type का होगा 
int breadth;
int height;
public int getVolume() {                 // volume निकालने का function
return (length * breadth * height);
}
Constructor1() {                        // बिना parameters का constructor
length = 10;
breadth = 10;
height = 10;
}
Constructor1(int l, int b, int h) { // तीन parameters int l,int b int h के साथ constructor 
length = l; //lenght variable mein l को store kar
breadth = b;
height = h;
}
public static void main(String[] args) {
Contructor1 contructorObj1, constructorObj2;
constructorObj1 = new Contructor1();
contructorObj2 = new Contructor1(10, 20, 30);


System.out.println("Volume of Constructor1 is : " + constructorObj1.getVolume());
System.out.println("Volume of Constructor1 is : " + constructorObj2.getVolume());
}
}

No comments:

Post a Comment