Question 9 • Page 4
What is a Constructor in Java?
- Purpose: Constructor ek special member hai jiska upyog object ko initialize karne ke liye kiya jata hai. A special member used to initialize objects when they are created.
-
Rules:
Constructor ka naam class ke naam ke saman hota hai aur iska koi return type nahi hota —
voidbhi nahi! Must have the exact same name as the class and has no return type (not evenvoid). -
When Called:
Jab hum
newkeyword se object banate hain, to constructor automatically call hota hai. Automatically invoked whenever an object is created with thenewkeyword.
Types of Constructors in Java
1. Default Constructor
Compiler khud provide karta hai jab koi constructor na likha ho.
Provided by Java compiler if no constructor is defined.
Default
class S { int age; public static void main(String[] args) { S s1 = new S(); System.out.println(s1.age); } }
Output0
2. No-Argument Constructor
Programmer bina parameters ke khud define karta hai.
Explicitly defined by the programmer with zero parameters.
No-Arg
class S { S() { System.out.println("No-argument"); } public static void main(String[] args) { S s1 = new S(); } }
OutputNo-argument
3. Parameterized Constructor
Parameters lekar object ko custom values se initialize karta hai.
Accepts parameters to initialize an object with specific values.
Parameterized
class S { int age; S(int age) { this.age = age; } void d() { System.out.println(age); } public static void main(String[] args) { S s1 = new S(20); s1.d(); } }
Output20