A constructor in Java is similar to a method that is invoked when an object of the class is created.
जावा में एक कंस्ट्रक्टर एक Method के समान होता है जिसे क्लास का ऑब्जेक्ट बनाते समय Invoked (USE) किया जाता है।
Unlike Java methods, a constructor has the same name as that of the class and does not have any return type.
Java Methods के विपरीत, एक कंस्ट्रक्टर का नाम Method के समान होता है और इसका कोई रिटर्न Type नहीं होता है।
For example,
class Test {
Test() {
// constructor body
}
}
Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return type.
यहाँ, टेस्ट () एक कंस्ट्रक्टर है। इसका नाम Class के समान है और इसका कोई रिटर्न Type नहीं होता है।
Program for constructor
class Main {
private String name;
// constructor
Main() {
System.out.println(
"Constructor Called:");
name =
"Programiz";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj =
new Main();
System.out.println(
"The name is " + obj.name);
}
}
Output:
Constructor Called:
The name is Programiz
No comments:
Post a Comment