|
Java Tutorial |
ConstructorThese pages make up the course notes for my Java programming course (run at Dallam, Milnthorpe, Cumbria). Hopefully they also make a useful self-learning tutorial. Sometimes when we create an object from a class we want somethings to be set up, or set to default values. Java provides a constructor method to do this. A constructor method has a slightly different method signature froma normal method. A normal method has a type (e.g. void, String, etc) whereas a construtor has no type, it also has the same name as the class (including the upper/lower case). Here is an example:
package tuorial.files;
public class Bookmarks {
public String url;
public String title;
public String file;
/**
* constructor, set up a default file name if none supplied
*
* @param file - the name of the bookmark file or null to default
*/
public Bookmarks(String file) {
if (file == null) {
this.file = "Bookmarks.html";
}
else {
this.file = file;
}
}
...
}
Notice that this contructor takes a parameter (file). This means that we must supply a file name when we make objects from this class - notice also that it handles the situation of the file name being null. If the file is null a default value is used. Constructors may have any number of parameters, or they may have none. This work is Copyright Chris Hunter 2007, you may use it for non-commercial purposes |