Object Oriented Programming

oatmealbrothersΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 4 μήνες)

76 εμφανίσεις

Object Oriented
Programming


Collections

Briana B. Morrison

CSE 1302C

Spring 2010

2

CSE 1302C

Topics


What is OOP?


Why OOP?


Collections

3

CSE 1302C

Object
-
Oriented Design Goals


Software should be:


robust


adaptable


reusable


How does OOD address these?

4

CSE 1302C

Object
-
Oriented Design Principles


Abstraction


Encapsulation


Modularity

5

CSE 1302C

Collections


Arrays are good for fast/immediate access
to the data, but their limitation is that they
are fixed in size. To overcome this,
collections that are dynamic allow us to
grow/shrink the data structure.



High
-
level APIs provide a means to access
these dynamic collections similar to arrays
(and use the [ ] index notation), but realize
that there is a lot of memory management
that is happening behind the scenes.


6

CSE 1302C

ArrayList


Many languages provide a means to manage polymorphic
collections such as the
ArrayList

(in C#).


This is polymorphic in that it holds elements of type "object", and
all classes implicitly inherit from "object". This is what provides
the "Equals()", "
ToString
()", etc. methods that all things have.



Sample syntax:


ArrayList

collection = new
ArrayList
();

collection.Add
(42);

collection.Add
("Dog");

collection.Add
(new Vector2(5,7));



This is permissible because the
int
, string, and Vector2 class are
all instances of the "object" class (via inheritance).


7

CSE 1302C

ArrayList


The problem with the
ArrayList

(and any polymorphic
collection) is that you must be careful in handling the data
when you access it.



You could not, for example do something like this (since all
elements may not be
ints
):


foreach

(
int

i

in collection)

{


// do something

}



This may generate an invalid typecast exception.

8

CSE 1302C

Parameterized Collections


To overcome the limitations of polymorphic collections (and
for performance/memory issues that we won't get into right
now), modern languages also provide a means by which
you can explicitly state the type of thing you want the
collection to manage. You do this via a "parameter" to the
class when you define it.



For example, we can use the List<T> class in C# to
accomplish this (where T is the type we want the list to
hold).


List<
int
> numbers = new List<
int
>();

numbers.Add
(42);

numbers.Add
(9);

9

CSE 1302C

List class


Some useful methods/attributes of the
List<T> class are:




Count



Capacity



Add()



RemoveAt
(
int
)



Insert(
int,T
)



10

CSE 1302C

List class


Since the type that the collection holds is known, we
can do something like this:


foreach

(
int

i

in numbers)

{


Console.WriteLine
(
i
);

}



And you can also access the elements via the [ ]
index notation as in:


numbers[0] = 8;

11

CSE 1302C

Questions?