#java #oop #programming #computerscience
Source: Dev.to
Java Concepts I’m Mastering – Part 4: Constructor vs Method
What is a Constructor?
A constructor is a special block of code that:
- Has the same name as the class
- Is called automatically when an object is created
- Initializes object data
class Student {
String name;
Student(String name) {
this.name = name;
}
}
It runs when you create an instance:
Student s1 = new Student("Kanishka");
What is a Method?
A method:
- Has a return type (or
voidif it returns nothing) - Is called explicitly by the code
- Performs actions on the object’s data
class Student {
String name;
void display() {
System.out.println(name);
}
}
It runs only when you invoke it:
s1.display();
Key Differences
- Purpose: Constructors build/initialize the object; methods define its behavior.
- Invocation: Constructors are invoked automatically with
new; methods require an explicit call. - Naming: Constructor name must match the class name; method names are independent.
- Return Type: Constructors have no return type; methods declare one (or
void).
What I Learned
- Constructors build the object.
- Methods define its behavior.
- Clean class design depends on understanding both.
Next in the series
Method Overloading in Java.