
Method vs Constructor
JavaSeries
30 November, 2023
17
17
1
Contributors
- In Java, if we keenly observe a constructor pretty much looks like a method, So let's see the major differences between a
constructor
and amethod
.
Point.java
package DevLearn.src;
public class Point {
public int x;
public int y;
// a constructor
public Point(int a, int b) {
x = a;
y = b;
}
// a method
public void setPoint(int a, int b) {
x = a;
y = b;
}
}
- So as we can see from the example,
constructor
would always have same name as the class & has no return type. The first letter should always be capitalized- Where as the
method
needs to have the return type. - Also the constructor can be called only while initializing the object where as we are free to call a method as many times as we would like