Java Reference
In-Depth Information
function: an object method. The object field is accessed using the reserved
keyword
this
.
Program 8.9
Object methods for the list
class
ListObj
int
container ;
ListObj next ;
ListObj(
int
element , ListObj
tail )
{
this
.container=element;
this
.next=tail;
}
ListObj insert (
int
s)
{
return new
ListObj(s ,
this
);
}
// Method
int
head ()
{
return this
.container;
}
}
In the
main
procedure, we could have then used the following instructions:
ListObj list=
new
ListObj (7 ,
null
);
list=list . insert(4);
System . out . println (
"Head:"
+list .head());
In the remainder, we will adopt this object-oriented framework when designing
data-structures, as they correspond to a true data encapsulation.
4
We will first
present the (class) static function and then describe the corresponding object-
oriented data-structure.
As concisely mentioned in the introduction, we made a difference between data-
structures with static functions operating on them, and encapsulated methods
acting directly on the object itself. We shall further describe these concepts
of object-oriented programming and revisit former data-structures using that
framework (replacing static functions by equivalent object methods).
To start with, consider the following example where one has to compute
the volume of a 3D box. First, we define a
Box
object by writing its class
encapsulating its data members:
width
,
height
,and
depth
. So far, the usual
way to process a
Box
has been using static functions that were necessarily
attached to a class. So let us define the
static double Volume(Box box)
function inside the body of the main class program. Note that this static
function needs a
Box
object as argument. The second (and much better way) to
program this functionality is to provide a
method
to the object that will dispose
of all the object fields at the time it is called. We access the various object fields
4
A second more advanced course will then purposely describe the
public
/
private
keyword syntax.
Search WWH ::
Custom Search