Object oriented
programming
Object oriented programming
OOP has three main tenants; we will go into each of
these as the semester progresses
Encapsulation of
the data and the operations on the data
Information hiding: this protects the data from unintended side effects
Polymorphism:
one command is capable of doing many things.
Encapsulation is
done in a class
Suppose we want to keep data about dogs
We would create a
dog class
What data would we want to keep track of if we had a
dog kennel with lots of dogs?
We create a template whose information we will fill in
for each individual dog.
The data we want to keep track of are the attributes
of each dog.
In Java, each bit
of data is called an instance variable.
Each individual dog is an object of the dog
class.
Creating a Dog class
First we have to declare the instance variables we want to keep track of for all dogs.
Next we have to decide what actions we want to take on
those attributes.
There are two standard actions usually used
Accessors retrieve the value of the instance variable
Mutators change the value of the instance variable
Actions are carried out by Java methods
These methods are encapsulated with the data
Java methods
A method has a header and a body
The header consists of
A return type
A name
Arguments
Think of the arguments as the information that goes in
to the method,
The return type is the information that comes out
The name should describe what the method does
An accessor: String getColor( );
A mutator: void setColor(brown);
Java method bodies
The body of a method is the executable code that
carries out the action required
For accessor and mutator methods, the body is simple
An accessor:
String
getColor( )
{ return color; }
A mutator:
void setColor(String
col)
{ color = col; }
Calling the methods
When we asks a
method to perform its action, it is calling the method
In order to call setColor(
) we must have a dog object whose color
we want to set
So we must
declare a Dog object this way
Dog zelda = new Dog( );
Then call the
method this way zelda.setColor(brown);
Putting it all together
The attributes (instance variables) and the methods
that act on them are encapsulated in one file
Instantiating objects (creating objects) and acting on
those objects with the methods are put into another file with a main method.