This site requires JavaScript, please enable it in your browser!
Greenfoot back
dejong1968
dejong1968 wrote ...

2020/2/22

What is a constructor

dejong1968 dejong1968

2020/2/22

#
I've searched for what a constructor exactly is, but I can't seem to find a clear answer. In this video , fom 09 - 13 sec the author says that "a constructor is a special method that runs when you first create an object". So I conclude a constructor is a method... (special method). Then, at 22-23 sec he says that the Circle() - part is the constructor. Now I'm confused... So my question is: is a constructor the special method as a whole or is a constructor the Circle()-part within a method that has no return type (and is named exactly like the class-name). Thanks!!
danpost danpost

2020/2/22

#
dejong1968 wrote...
fom 09 - 13 sec the author says that "a constructor is a special method that runs when you first create an object". So I conclude a constructor is a method... (special method). Then, at 22-23 sec he says that the Circle() - part is the constructor
He was definitely not clear as to what he was trying to say. This line:
Circle c = new Circle();
does not contain a constructor. "Circle()" is the name of a constructor and "new Circle()" calls that constructor to execute, creating a new Circle object. A constructor looks exactly like a method, except for two major detail ... it does not have a return type in its declaration line and it will always be named with the class name.
/** methods */
public void show() { ... } // 'void' : returns nothing

void update() { ... } // 'void' : returns nothing

public Point getOrigin() { return origin; } // 'Point' : returns a Point object

int getSize() { return getImage().getWidth(); } // 'int' : returns an int value

/** constructors */
public MyWorld() { super(600, 400, 1); prepare(); } // creates and returns (by default) a new MyWorld object (in MyyWorld class)

public Circle() { ... } // creates and returns a new Circle object (in Circle class)

public MyWorld(Counter counter) { super(600, 400, 1); this.counter = counter; prepare(); } // in MyWorld class
The last one has an already created Counter object passed to it for it to use (useful in maintaining a score when going from one level to another).
You need to login to post a reply.