Recent Changes - Search:

Java Tutorial

edit SideBar

Constructor

These 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.

 

Creative Commons License

This work is Copyright Chris Hunter 2007, you may use it for non-commercial purposes
under the Creative Commons license Creative Commons Attribution-Noncommercial-Share Alike.

Edit - History - Print - Recent Changes - Search
Page last modified on July 18, 2007, at 02:07 PM