Intern
What is the difference between a method and a constructor?
sobes.tech AI
Answer from AI
Method - a block of code that performs a specific task and can be called by name. It can return a value and accept parameters.
Constructor - a special method used to initialize objects of a class. It has the same name as the class, does not have a return type (not even void), and is called when creating an object using the new operator.
| Criterion | Method | Constructor |
|---|---|---|
| Purpose | Performs actions | Initializes an object |
| Name | Arbitrary (according to naming rules) | Same as the class name |
| Return type | Can be any (including void) |
Has no return type (not even void) |
| Call | Explicitly called by object name | Called automatically when creating an object |
| Inheritance | Can be inherited | Cannot be inherited |
| Abstractness | Can be abstract | Cannot be abstract |
public class Example {
private int value;
// This is a constructor
public Example(int value) {
this.value = value; // Initialize class field
}
// This is a method
public int getValue() {
return value; // Return the field value
}
// This is another method
public void setValue(int value) {
this.value = value; // Change the field value
}
/* Another method */
public static void main(String[] args) {
Example obj = new Example(10); // Call constructor to create object
System.out.println(obj.getValue()); // Call getValue() method
obj.setValue(20); // Call setValue() method
System.out.println(obj.getValue());
}
}