🟣 OOP · Lesson 18
Constructors
What is a Constructor?
A constructor is a special method that runs automatically when an object is created. It sets up the object's initial values. It has the same name as the class and no return type.
Parameterized Constructor
class Student {
String name;
int marks;
Student(String n, int m) { // constructor
name = n;
marks = m;
}
}
Student s = new Student("Riya", 95);
System.out.println(s.name + " " + s.marks);Riya 95
Summary
- A constructor runs on object creation; same name as class, no return type.
- Parameterized constructors set initial values directly.
Constructor क्या है?
Constructor एक special method है जो object बनते ही अपने आप चलता है। यह object की initial values set करता है। इसका नाम class जैसा होता है और कोई return type नहीं।
Parameterized Constructor
class Student {
String name;
int marks;
Student(String n, int m) { // constructor
name = n;
marks = m;
}
}
Student s = new Student("Riya", 95);
System.out.println(s.name + " " + s.marks);Riya 95
सारांश
- Constructor object बनने पर चलता है; नाम class जैसा, कोई return type नहीं।
- Parameterized constructors initial values सीधे set करते हैं।
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.