I know constructor is a special member of class use to initialize data member..But why we actually need constructor can somebody tell me.
Asked
Active
Viewed 266 times
0
-
1_"...to initialize data member"_ - this is exactly why constructor is used. It initializes the newly created instance. – Yousaf Nov 29 '21 at 05:41
-
6Does this answer your question? [Purpose of a constructor in Java?](https://stackoverflow.com/questions/19941825/purpose-of-a-constructor-in-java) – zysaaa Nov 29 '21 at 05:47
-
Because we need to. An object is created using a constructor by definition. This is not Java specific, this is about class based object orientated development. Some languages though, like the infamous _ECMAScript_ aka "JavaScript" copy/link prototypes instead of instantiating classes. – Amadán Nov 29 '21 at 08:05
1 Answers
-1
We can use constructor to set it's fields.
public class FutilePoint {
private double x, y, size;
private int color;
public FutilePoint(double pos_x, double pos_y, double size, int color_RGB) {
this.x = pos_x;
this.y = pos_y;
this.size = size;
this.color = color_RGB;
}
public FutilePoint(pos_x, pos_y) {
this.x = pos_x;
this.y = pos.y;
this.size = 4;
this.color = 0x000000;
}
}
Then we can create many different objects.
#import src.FutilePoint;
//somewhere in a random class...
public void doMeaninglessStuff() {
for(int i = 1; i <= 99999999; i++) {
for(int j = 1; j <= 99999999; j++) {
new FutilePoint(i, j);
}
}
new Point(0, 0, 128, 0xFFFF3A);
}
You can also use it's methods in the constructor.

George Glebov
- 173
- 8