Java Reference
In-Depth Information
secondStudent.id = 2;
secondStudent.firstName = "Sophie";
System.out.println("The student object referred to "+
"by the variable secondStudent has the first "+
"name: "+secondStudent);
}
2.
You should now be able to run the
Student
class from Eclipse and observe the output given on the
console.
How It Works
Now take a look at how it works.
1.
The
new
keyword is used to create objects, which you will use to create a bunch of students. Note the
use of the dot (
.
) operator in this code to access (
read
and
write
) the Student objects' variables.
2.
As Java is a fully object‐oriented program, however, you need to find an appropriate place to create
the students. Loose scripts cannot exist in Java, meaning that you have to create the students inside
a method definition of a class.
3.
To actually execute, that is, run the program, you add a so‐called
main
method to the
Student
class.
As Java has no way of knowing which particular method you want to use as the entry point of the
program, a special method exists—the so‐called
main
method—that serves exactly this purpose.
4.
When running this program from Eclipse, Java will call the class'
main
method. The
main
method
will create some students, set their variables, and print some information to Eclipse's console.
5.
You might be wondering what the
public
and
static
keywords are doing before the
main
method
definition. Don't worry about these too much for now. You will see what
static
does later on in this
chapter and learn about the role of
public
in Chapter 8. For now, just keep in mind that the
main
method must be
public
,
static
, return nothing (
void
), and take a single argument: an array of
strings,
String[]
. The name of the argument can be changed, but by convention,
args
is used. The
reason for this is that this method argument will contain the list of arguments that was passed to Java.
6.
Note that, generally speaking, mixing in this
main
method with the student class definition is not
a good idea. Ask yourself the following: is a student responsible for creating some students? The
answer is, of course, no.
7.
As such, you can also put this program logic somewhere else. The question is then, of course,
where? Think about this, which
class of objects
should
be responsible for the behavior
of creating
some students? You might come up with different answers. For example, you might say, “I just
want my program to create some students.” So what you can do is add a class, called
MyProgram
,
to hold a single
main
method:
class MyProgram {
// I am the program managing your Student and Course objects.
public static void main(String[] args) {
Student firstStudent = new Student();
Student secondStudent = new Student();
firstStudent.id = 1;
firstStudent.firstName = "Marc";
Search WWH ::
Custom Search