Professional Documents
Culture Documents
Week 5 - Lecture 2 - Chapter 10
Week 5 - Lecture 2 - Chapter 10
• The this keyword is the name of a reference that refers to an object itself.
• One common use of the this keyword is to reference a class’s hidden data
fields.
• Another common use of the this keyword is to enable a constructor to invoke
(call) another constructor of the same class.
10.4 THE THIS REFERENCE (CONTINUED)
4
public class Foo { Suppose that f1 and f2 are two objects of Foo.
private int i = 5;
Calling f1.setI(10) will execute
this.i = 10, where this refers f1
public void setI(int i) { The above assigns the value 10 of the
this.i = i; parameter i to the data field i.
}
Invoking f2.setI(45) will execute
} data field parameter this.i = 45, where this refers f2
10.4 THE THIS REFERENCE (CONTINUED)
5
} parameter parameter
10.4 THE THIS REFERENCE (CONTINUED)
6
Person Address
- name: String - building: String
- address: Address - street: String
- city: String
+ Person(n: String, a : Address)
+ toString( ): String + Address(b: String, s: String, c: String)
+ toString( ): String
private Address address; // This is the statement that creates the composition relationship.
name = n;
address = a;
}
10.8 DESIGNING THE COURSE CLASS
9
UML Diagram of class Course + description of the methods.
Course
+Course(name: String, size: int) Creates a Course with the specified name.
+getName( ): String Returns the course name.
+addStudent(student: Student): void Adds a new student to the course list.
+getStudents( ): Student[ ] Returns the students for the course.
+getNumberOfStudents( ): int Returns the number of students for the course.
+ print( ): void Outputs the data fields of the class.
In your textbook the type of the array students is String, but here we
changed the type to Student to make the problem more interesting.
10.8 (CONTINUED)
10
UML Diagram of classes Course and Student.
Course Student
-name: String
-id: int
-students: Student[ ]
-name: String
-numberOfStudents: int
+Student(id: int , name: String)
+Course(name: String, size: int)
+getId( ): int
+getName( ): String
+getName( ): String
+addStudent(student: Student): void
+setId(id: int ): void
+getStudents( ): Student[ ]
+setName(name: String): void
+getNumberOfStudents( ): int
+ print( ): void
+ print( ): void
In your textbook the type of the array students is String, but here we
changed the type to Student to make the problem more interesting.
public class Student {
Code of class Student
private
11 int id;
private String name;
}
} // end Application
10.8 (CONTINUED)
15