Spaces:
Running
Running
this.<attributeName> = paramName;
Browse files
Week 4: Writing classes/06a. Keyword this
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
So, the constructor is usually passed parameters, and it sets the values of the attributes according to these parameters.
|
| 2 |
+
|
| 3 |
+
For example, a class that models a book:
|
| 4 |
+
class Book {
|
| 5 |
+
String name;
|
| 6 |
+
String writer;
|
| 7 |
+
int pages;
|
| 8 |
+
int releaseYear;
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
public Book(String n, String w, int p, int ry) {
|
| 12 |
+
name = n;
|
| 13 |
+
writer = w;
|
| 14 |
+
pages = p;
|
| 15 |
+
releaseYear = ry;
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
In the example, you will notice that the PARAMETER NAMES are somewhat clumsy ABBREVIATIONS of the attribute names.
|
| 21 |
+
Now, when calling the constructor, it is not at all clear what the parameters actually mean.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
-------------------------
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
A better way is to USE the SAME IDENTIFIERS for parameters and attributes.
|
| 28 |
+
This can be done by using the keyword 'this':
|
| 29 |
+
|
| 30 |
+
class Book {
|
| 31 |
+
String name;
|
| 32 |
+
String writer;
|
| 33 |
+
int pages;
|
| 34 |
+
int releaseYear;
|
| 35 |
+
|
| 36 |
+
public Book(String name, String writer, int pages, int releaseYear) {
|
| 37 |
+
this.name = name;
|
| 38 |
+
this.writer = writer;
|
| 39 |
+
this.pages = pages;
|
| 40 |
+
this.releaseYear = releaseYear;
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
The keyword 'this' refers to the CURRENT OBJECT.
|
| 46 |
+
|
| 47 |
+
Thus the entry
|
| 48 |
+
'this.name'
|
| 49 |
+
always refers to the attribute name of the object.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
In the constructor above, the statement
|
| 53 |
+
this.name = name;
|
| 54 |
+
sets the attribute value to the name received as a parameter.
|
| 55 |
+
In effect, the name given by the client is set as the value of the name field of the new object to be created.
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
|