Would appreciate a detailed explanation of constructors
I am trying to learn Java on my own during my free time, and as with most programming languages, doing so without proper instruction can be a daunting task. Several years ago I learned Visual Basic, and although it is a somewhat useless and oftentimes disrespected language, it provided for me enough background and experience to inspire me to pick up a more 'useful language'.
To get to the point, after several hours of searching web pages and reading through the java tutorial, I have yet to understand exactly what the purpose of a constructor is.My main problem is understanding the tutorial program CreateObjectDemo:
http://java.sun.com/docs/books/tutorial/java/javaOO/objects.html
If my compiler (JCreator...is there another I should use?) would allow me to 'step' through the program as it executed, I could follow the flow of it and understand, but as I cannot do that, I have code that, although functional, is a mystery to me. Here are the three classes it uses.
publicclass CreateObjectDemo{
publicstaticvoid main(String[] args){
//Declare and create a point object
//and two rectangle objects.
Point originOne =new Point(23, 94);
Rectangle rectOne =new Rectangle(originOne, 100, 200);
Rectangle rectTwo =new Rectangle(50, 100);
//display rectOne's width, height, and area
System.out.println("Width of rectOne: " +
rectOne.width);
System.out.println("Height of rectOne: " +
rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());
//set rectTwo's position
rectTwo.origin = originOne;
//display rectTwo's position
System.out.println("X Position of rectTwo: "
+ rectTwo.origin.x);
System.out.println("Y Position of rectTwo: "
+ rectTwo.origin.y);
//move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: "
+ rectTwo.origin.x);
System.out.println("Y Position of rectTwo: "
+ rectTwo.origin.y);
}
}
publicclass Point{
publicint x = 0;
publicint y = 0;
// a constructor!
public Point(int a,int b){
x = a;
y = b;
}
}
publicclass Rectangle{
publicint width = 0;
publicint height = 0;
public Point origin;
// four constructors
public Rectangle(){
origin =new Point(0, 0);
}
public Rectangle(Point p){
origin = p;
}
public Rectangle(int w,int h){
origin =new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p,int w,int h){
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
publicvoid move(int x,int y){
origin.x = x;
origin.y = y;
}
// a method for computing the area of the rectangle
publicint getArea(){
return width * height;
}
}
I'm sorry for the long post, but I am at a loss as to what the flow of this program is, and as many times as I read various definitions for constructors, I feel I will never understand it without a dumbed-down explanation, or seeing the flow in progress. Any help is greatly appreciated.
[5722 byte] By [
Baelratha] at [2007-11-27 10:44:05]

The job of a constructor is to initialize an object so as to give it a consistent state.
I don't know what specific problem you're having with that code or with understanding the purpose of constructors, so all I can say is this:
A constructor is invoked as part of the object creation process. Its job is to put the object into a valid state. Often times this simply means setting member variables based on values passed as parameters, but sometimes the setup may be more complex.
For example, if you have a Person class, your rules might dictate that a Person object is meaningless and useless without a name, birthdate, and social security number.
public class Person {
private String lastName;
private String firstName;
private final Date birthDate;
private final String ssn;
public Person(String lastName, String firstName, Date birthDate, String ssn) {
if (lastName == null || fistName == null | birthDate == null || ssn == null) {
throw new IllegalArgumentExcption("all fields must be non-null");
}
this.lastName = lastName;
this.firstName = firstName;
this.birthDate = new Date(birthDate.getTime()); // since Date is mutable
// now call method that validates that ssn is xxx-xx-xxxx or xxxxxxxxx
// and if invalid, throw new IllegalArgumentException
this.ssn = ssn;
}
}
So when we create a Person object, we make sure that all the required fields have valid values, and set them appropriately.
jverda at 2007-7-28 20:04:45 >

> If my compiler (JCreator...is there another I should
> use?) would allow me to 'step' through the program as
> it executed,
I'm surprised JCreator doesn't have a debugger. Eclipse does, as does any decent IDE.
Absent that, you can certainly add a bunch of System.out.printlns so you can see what's happening.
jverda at 2007-7-28 20:04:45 >

My main problem of understanding was this:
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
The fact that it had four constructors that basically all did the same thing, but each one had different required variables that it needed to be sent. In my mind, whenever the program called the Rectangle constructor, it went through each of the four, and that's where I got confused.
I suddenly had an epiphany, and correct me if I'm wrong here, but those four constructors are to basically fill in the gaps based on how much information was sent, thereby preventing errors if you, for instance, decided to only send the width and height, and didn't mention an origin. It isn't going through all four, but rather just the ones that are needed based on what information you sent.
Correct?
> > If my compiler (JCreator...is there another I
> should
> > use?) would allow me to 'step' through the program
> as
> > it executed,
>
>
> I'm surprised JCreator doesn't have a debugger.
> Eclipse does, as does any decent IDE.
>
> Absent that, you can certainly add a bunch of
> System.out.printlns so you can see what's happening.
You could also use jdb.
http://java.sun.com/j2se/1.3/docs/tooldocs/solaris/jdb.html
Here is some general information about constructors.
1. Constructors are not inherited into subclases.
2. A class that has no constructors is given exactly one.
A default, no argument costructor of public access.
3. A constructor can call upon other constructors in the
class for help, using the this() construct at the begin.,
of the constructor.
4. A constructor can call a specific constructor of the
parent class by using the super() construct at the begin.,
of the constructor.
5. If you do not provide a call to either this() or super(),
then Mr. Compiler creates a call to super() for you.
6. If you extend a class that has no zero argument constructor
or that constructor is not accessible in the sub class, then
you can't allow the default call to super(). You must have an
explicit call to a form of super() that you can access.
> I suddenly had an epiphany, and correct me if I'm
> wrong here, but those four constructors are to
> basically fill in the gaps based on how much
> information was sent, thereby preventing errors if
> you, for instance, decided to only send the width and
> height, and didn't mention an origin.
The reasons for having different c'tors are:
* Different ways of specifying the same information. For instance one to take a Date for birthdate, and one to take a String, which then internally gets parsed into a Date.
* Be able to only specfy certain values, and allow defaults to be used for others. For instance, if an origin isn't specified, maybe assume an origin of (0, 0). If a Date isn't specified, assume today.
> It isn't going
> through all four, but rather just the ones that are
> needed based on what information you sent.
Close. It uses exactly the one that you explicitly specify by which args you passed (although that one may internally invoke another one).
jverda at 2007-7-28 20:04:45 >
