When you create an object with new, a special method runs to set it up — a constructor. Constructors give an object its starting values so it's ready to use. This is a core ICSE Class 10 topic.
1What a constructor is
A constructor is a special method that runs automatically when an object is created, to initialise it. Its features:
- It has the same name as the class.
- It has no return type — not even
void. - It runs automatically with
new; you don't call it by name.
class Student {
String name;
int marks;
Student() { // constructor (same name as class)
name = "Unknown";
marks = 0;
}
}
Student s = new Student(); // the constructor runs here
- A constructor is a special method that initialises an object when it is created.
- It has the same name as the class and NO return type (not even void).
- It runs automatically when you use new — you don't call it by name.
2Default vs parameterised constructors
| Default constructor | Parameterised constructor | |
|---|---|---|
| Parameters | None | Takes values as parameters |
| Sets values to | Fixed defaults | Whatever you pass in |
Student() { // default constructor
name = "Unknown";
marks = 0;
}
Student(String n, int m) { // parameterised constructor
name = n;
marks = m;
}
Student a = new Student(); // uses default
Student b = new Student("Asha", 92); // uses parameterised- A default constructor takes no parameters and sets fixed default values.
- A parameterised constructor takes values and initialises the object with them.
- If you write no constructor, Java provides an invisible default one.
3Constructor overloading & vs methods
Constructor overloading means having several constructors in one class with different parameter lists — so objects can be created in different ways:
Student() { ... } // no args
Student(String n) { ... } // name only
Student(String n, int m) { ... } // name and marksConstructor vs ordinary method
| Constructor | Method | |
|---|---|---|
| Name | Same as the class | Any valid name |
| Return type | None | Has one (or void) |
| When it runs | Automatically, on object creation | When you call it |
| Purpose | Initialise the object | Perform any task |
- Constructor overloading = several constructors with different parameter lists.
- A constructor has the class's name, no return type, and runs automatically on new.
- A method has any name, a return type, and runs only when called.
★ Practical: construct objects
In BlueJ, build a class Book that:
- Has a default constructor setting title to "Untitled" and price to 0.
- Has a parameterised constructor Book(String t, double p).
- Creates one object each way and prints their values.
- List two differences between your constructor and your display() method.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.