Spaces:
Running
Running
| So, the constructor is usually passed parameters, and it sets the values of the attributes according to these parameters. | |
| For example, a class that models a book: | |
| class Book { | |
| String name; | |
| String writer; | |
| int pages; | |
| int releaseYear; | |
| public Book(String n, String w, int p, int ry) { | |
| name = n; | |
| writer = w; | |
| pages = p; | |
| releaseYear = ry; | |
| } | |
| } | |
| In the example, you will notice that the PARAMETER NAMES are somewhat clumsy ABBREVIATIONS of the attribute names. | |
| Now, when calling the constructor, it is not at all clear what the parameters actually mean. | |
| ------------------------- | |
| A better way is to USE the SAME IDENTIFIERS for parameters and attributes. | |
| This can be done by using the keyword 'this': | |
| class Book { | |
| String name; | |
| String writer; | |
| int pages; | |
| int releaseYear; | |
| public Book(String name, String writer, int pages, int releaseYear) { | |
| this.name = name; | |
| this.writer = writer; | |
| this.pages = pages; | |
| this.releaseYear = releaseYear; | |
| } | |
| } | |
| The keyword 'this' refers to the CURRENT OBJECT. | |
| Thus the entry | |
| 'this.name' | |
| always refers to the attribute name of the object. | |
| In the constructor above, the statement | |
| this.name = name; | |
| sets the attribute value to the name received as a parameter. | |
| In effect, the name given by the client is set as the value of the name field of the new object to be created. | |