Java Reference
In-Depth Information
How It Works
Now take a look at how it works.
1.
You're creating two new
Student
and
Course
classes in a new Eclipse project.
2.
For the
Course
class, note the use of the
nextId
variable to automatically use an incrementing coun-
ter to provide IDs for courses. This is a well‐known pattern that you will see show up commonly in
Java code. Also note the use of the
HashSet
object. A
HashSet
is a set, storing a bunch of objects
(
Student
objects, in this case). The
HashSet
class is built‐in by default in Java, but to enable its use,
you first have to import it, hence the
import
statement before defining the class itself. Don't concern
yourself too much with its usage for now, but make sure you understand the
registerStudent
and
unregisterStudent
methods, which add and remove students to and from the set.
3.
For the
Student
class, you're using the keyword
this
to pass the current student object (meaning
the object the method was called on) to the course object to register or unregister a student, as it is
the course object that keeps a list of registered students.
4.
The
Program
class contains the
main
method, and it creates two courses, gives some information
about them, creates two students, and registers them in the courses. The
p
method just serves as a
shorthand to avoid having to write
System.out.println
all the time.
5.
You then run this program from Eclipse by invoking the
main
method in the
Program
class. Note
that it is possible at this point to create another class containing a
main
method and run that one in
Eclipse by just making sure the
main
method you want to run is open in the code editor.
access modifiers
You might have noticed that this code uses
courseA.id
(directly accessing a vari-
able) and
courseA.getName()
(accessing a variable through a method) in the Try
It Out. In other examples, you read that it's generally better to access variables
through methods whenever possible instead of directly accessing variables.
If it is generally recommended to go through methods, then why does Java allow
you to access
courseA.id
directly? The reason for this is due to the access modifier
being used. Classes, variables, and methods can all take access modifiers. In Java,
four access modifiers exist:
public
: For classes, methods, and member variables (class or instance)
protected
: Methods and member variables (class or instance) (not for classes)
no modifier:
: For classes, methods, and member variables (class or instance)
private
: Methods and member variables (class or instance) (not for classes)
You have seen one of these (
public
) already, namely in the
main
method, where the
inclusion of this access modifier was mandatory:
public static void main(String[] args)
continues
Search WWH ::
Custom Search