Java Reference
In-Depth Information
to dispose of the point coordinates (
x, y
) and a triplet red/green/blue, say, for
encoding its color properties (
R, G, B
). For a student object, we may rather
define the following fields: Lastname, firstname, group, etc. Java is such an
object-oriented (OO) programming language.
We first start by presenting how to define and create objects, and then describe
howtowrite
non-static
functions acting on the object's records: methods.
Furthermore, we shall see how to create arrays of non-primitive elements: arrays
of objects. Finally, we will present the
String
class, which is a particular class
standardized in Java. We will quickly overview a set of methods that that class
offers.
5.2 Declaring classes and creating objects
To create objects, we first need to declare them by creating a new
class
for
structuring them. Objects are also typed structures: The class name defines
the type of objects. Once the object records are clearly identified in the design
stage, we create corresponding variable fields in the class by defining variables
without using the keyword
static
. Fields are also called
object variables
and
do not have the leading keyword
static
. Thus to create an object for storing
dates, we first define the corresponding class
Date
, which contains the fields
dd
,
mm
and
yyyy
for storing respectively the day, month and year of the date.
The class declaration for
Date
is as follows:
class Date
{
int dd; // field for day (no static keyword here!)
int mm; // field for month
int yyyy; // field for year
}
Let us suppose that we created an object
day
of type
Date
. Then the variable
dd
of
Date
(its record) and can be accessed by the programmer by writing
day.dd
: That is, the record
dd
of the object
day
. Similarly, the month and year
object records are accessed by writing
day.mm
and
day.yyyy
.
An object storing records of students can be similarly created from a
corresponding class
Student
that encapsulates the various data attached to
a student identity. Fields may not be all of primitive types. For example, we
may also attach to a student object an array of
double
for storing his/her exam
marks. Thus we may come up with the following class structure for defining
the class
Student
:
class Student
{
Search WWH ::
Custom Search