Vous êtes sur la page 1sur 77

Object Oriented Programming I

COMPILED BY MICHAEL JONES

COMPILED BY MICHAEL JONES

OOP I

What does object-oriented mean?


Programs consist of entities, called objects, which correspond
to concepts the program will manipulate:
A business application might have Employee and
Department objects.
Objects are created by specifying their structure and their
properties in a class.
The Employee class is a (single) blueprint used to create
(many and varying) Employee objects.
Objects communicate by sending each other messages:
We might ask an Employee object "what's your
name?".
COMPILED BY MICHAEL JONES

OOP I

What is object-orientedness?
A programming style where concepts in your problem domain
are mapped directly into your code: "object-oriented means
"concept-oriented."
A philosophy of design and implementation (i.e., a way of
thinking about your code) which can be employed even in
non-OO programming domains.
A technology to help you follow this philosophy: OO
languages, OO databases, OO expert systems, etc.
A buzzword used by people who want to sell you something.

COMPILED BY MICHAEL JONES

OOP I

What is object-orientedness not?


It is not a solution to all your design and implementation
problems.
It will not allow non-programmers to "program like the pros."
It does not allow you to side-step the design process and
begin coding applications from day zero.
It is not inherently better than non-OO for all tasks.
It will not grow hair, lower your cholesterol, taste as fresh as
homemade, soften hands while you do the dishes, and paint
any car for $99.95 beware of sales pitches, no matter how
flashy.

COMPILED BY MICHAEL JONES

OOP I
The Software crisis: why we must change our ways
Human society depending more and more on software.
The software crisis: much existing software is...
bug-ridden, because...
too complex to understand, and so...
difficult to maintain, and so...
difficult to extend, and so...
We reinvent the wheel over and over, leading to...
unnecessarily high development costs
new and more exciting bugs...

COMPILED BY MICHAEL JONES

OOP I
The Goal: Software reuse
Programs tend to be "stick built" from the ground up:
Like making custom nails, screws, bricks, etc. for a house!
Take our cue from the industrial revolution: assembly lines
and interchangeable parts:
Goal: develop manageable, understandable, reusable
software components that can be employed in a wide variety
of applications, so that "new" code is specific to the problem
at hand.
Reuse is not the same as "cut and paste"; however...
Temptation to "cut and paste" indicates useful code!
COMPILED BY MICHAEL JONES

OOP I
Benefits of Software reuse
Reduces coding/testing, thereby reducing delivery time and
cost.
Many re-users means many testers: well-tested code!
Bugs found in reusable module can be reported to source: fix
is made, new module is distributed, and now everyone
benefits.
Application programmers don't need to be experts in a wide
variety of esoteric disciplines: easier to hire developers, and
easier to keep them sane.
High visibility of code can improve attitude of developer, and
inspire more care and forethought, rather than just "task at
hand" thinking.
COMPILED BY MICHAEL JONES

OOP I
How does OOP help?
Message passing paradigm provides clear, consistent syntax
for accessing/manipulating objects.
Encapsulation provides way of making data and "helper
functions" inaccessible to prying eyes and sticky fingers.
Inheritance allows new data structures to be defined in terms
of existing ones, re-using existing (and tested) code.
Dynamic binding means that data structures keep track of
their types, so users of the data structures don't have to.
All objects come bundled with the complete set of functions
that are needed to work with them.
COMPILED BY MICHAEL JONES

OOP I
The OOP Universe
Objects

The four (4) building blocks

Classes

Encapsulation

Instance Variables

Inheritance

Instance methods and


messages

Abstraction
Polymorphism

Class variables/methods

Variable Scope

Types of Methods

Common keywords

Creating and reusing objects

super, this, instanceof

Composition
Code Reuse
COMPILED BY MICHAEL JONES

OOP I
What is an Object?
An object is a bundle of information that models some highlevel concept in the problem domain. In terms of
implementation an object is an instance of a class.
Generally a 1-to-1 correspondence between "real things" in
the problem domain and objects in a running OO program.
This is one reason that OO programs can be very intuitive
to work with: they're a kind of "virtual reality".
The structure and behavior of an object is defined in the
object's class description...
Objects have attributes, identity and behaviour
COMPILED BY MICHAEL JONES

10

OOP I
What is an Object?

COMPILED BY MICHAEL JONES

11

OOP I
Object Identify, Attribute, Behaviour
Identity what makes the object unique. E.g. A
student ID number. We focus on the current
(dynamic) values of each of these properties
State Characteristics of the object.
Behaviour What does the object do. Functions
implemented within the object usually determine
what an object will do.

COMPILED BY MICHAEL JONES

12

OOP I
Object Classes and Instances
A class is a blueprint for creating many similar objects.
The created object is an instance of that class.
Objects created from the same class will have the same
basic structure and functionality.
All cars created from the same Ford Escort blueprints
will look and work basically the same.
Many instances can be created from a single class.
Just as many Ford Escorts can be created from the
same set of Ford Escort blueprints
COMPILED BY MICHAEL JONES

13

OOP I
Object Classes and Instances

COMPILED BY MICHAEL JONES

14

OOP I
Instance Variables
An instance variable (or attribute) of an object is a piece
of information attached to an instance (object).
The name of a Person object, the model and year of a Car object,
etc.

The instance variables that an object has are defined in


the object's class: an object can usually have many
instance variables, of many different types.
Each object is given its own private space to hold its
instance variables. Assigning a new value to an instance
variable of one object does not affect the instance
variables of any other object.
COMPILED BY MICHAEL JONES

15

OOP I
Instance Methods
When we define objects, we usually have an idea of what
we want to do with them...
I'm dealing with Person objects in an employee database... I want
to be able to ask each Person object their name, weight,

and age.
I'm dealing with Car objects in a driving simulation... I
want to be able to start a Car, change its speed, turn
its steering wheel, etc.
An action that involves a single object as the "star player"
is usually implemented as a special kind of
function/subroutine attached to that object's class, called
an instance method (or, more commonly, just a method).
COMPILED BY MICHAEL JONES

16

OOP I
Methods and Messages
A message is the request you send to an object in order to
get it to do something: perform an action, return a value,
etc.
A method is the piece of code which is called to perform
the activity requested by the message:

Message passing and method invocation usually mean


the same thing: the act of sending
COMPILED BY MICHAEL JONES

17

OOP I
What messages look like
A message generally has three parts:
The receiver: the object receiving the message.

The method name: what we want the object to


execute.
The parameters: any arguments that the message
takes.

COMPILED BY MICHAEL JONES

18

OOP I
What methods look like

COMPILED BY MICHAEL JONES

19

OOP I
An OO bestiary

COMPILED BY MICHAEL JONES

20

OOP I
Class Methods
If a class is just another kind of object, then it should have
its own methods and respond to messages, right?
Right! Because of this, we usually divide methods into:
Class methods, which are invoked when you send a
message to a class.
Instance methods, which are invoked when you send a
message to an instance of a "normal" class.
We usually just call these methods.

COMPILED BY MICHAEL JONES

21

OOP I
Class Methods
Class methods generally do not operate on instances!
They are intended for performing utility functions that are
strongly associated with a class, but that don't involve any
particular instance of that class!
Other candidates for class methods:
Storing/retrieving objects of this class by some appropriate
lookup key (e.g., the name).

Asking for information related to the class as a whole:


Return the count of all vehicles created via this class
template

COMPILED BY MICHAEL JONES

22

OOP I
Class Variables
If a class is just another kind of object, then it should have its
own instance variables too, right?
Right! And these special instance variables are commonly
called class variables.
Class variables are variables declared with in a class, outside
any method, with the static keyword
In many OO environments, the only places you can access a
class variable are:
From inside a class method of that class
From inside an instance method of that class
Class variables are kind of like global variables which are
associated with a particular class.
COMPILED BY MICHAEL JONES

23

OOP I
Types of Methods
There are 3 basic types of methods in Java:
1. Modifier (sometimes called a mutator or setter)
Changes the value associated with an attribute of the
object (or class)
2. Accessor (sometimes called a getter)
Returns the value associated with an attribute of the
object (or class)
3. Constructor
Called once when the object is created (before any other
instance method can be invoked)
COMPILED BY MICHAEL JONES

24

OOP I
Types of Methods - Mutator
Mutator Methods are used to change the value of a variable
They are often called Setter Methods or just Setters
This is part of the OOP data encapsulation principle (more on
this later)

COMPILED BY MICHAEL JONES

25

OOP I
Types of Methods - Accessor
Is used to give visibility to the value of private field
Does not modify the contents of an Object
Usually returns the value of a field

COMPILED BY MICHAEL JONES

26

OOP I
Types of Methods - Constructor
As mentioned before, constructors are special functions used to
initialize or return a new object.
Depending on the OO environment, a class might have many
constructors, each of which builds an object a different way.
Different constructors will have the same name but be
distinguished by having different numbers/types of their
arguments.
Constructors also must have the same name of the class and
no explicit return type.

COMPILED BY MICHAEL JONES

27

OOP I
Types of Methods - Constructor
Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default
constructor for that class.
Each time a new object is created, at least one constructor will
be invoked.

COMPILED BY MICHAEL JONES

28

OOP I
Creating and Using Objects
As mentioned previously, a class provides the blueprints for
objects. So basically an object is created from a class. In Java,
the new key word is used to create new objects
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name
with an object type
Instantiation: The 'new' key word is used to create the
object
Initialization: The 'new' keyword is followed by a call to a
constructor This call initializes the new object

COMPILED BY MICHAEL JONES

29

OOP I
Creating and Using Objects
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.

println(Name arg: " + name );


}
public static void main(String []args){
//create an object myPuppy

Puppy myPuppy = new Puppy( "tommy" );


}
}
COMPILED BY MICHAEL JONES

30

OOP I
Composition
When an object contains another object, if the contained object
cannot exist without the existence of container object, then it is
called composition. You can apply the Part-Of rule here, for
example:
An Order Item is part of an Order

A Room is part of a Building


A Wing is part of a Plane
A Contact is part of an Address Book
A Contact Group is part of an Address Book
COMPILED BY MICHAEL JONES

31

OOP I
Composition
It is important to note that composition is a special for of
aggregation and we can call this a death relationship. It is a
strong type of aggregation. Child objects does not have their
lifecycle if the parent object is deleted; the child object is also
deleted. For example look at the relationship between Building
and Rooms. Building can contain multiple rooms, there is no
independent life of room. If we delete building, room will
automatically be deleted.

COMPILED BY MICHAEL JONES

32

OOP I
Composition
Composition defines a HAS A relationship.

class Engine {}

// The engine class

class Car{
// Cars have engines so, Car class has an instance of
//Engine class as its member.

private Engine engine;


}
COMPILED BY MICHAEL JONES

33

OOP I
Code Reuse
One of the most compelling features about Java is code reuse.
But to be revolutionary, youve got to be able to do a lot more
than copy code and change it
Thats the approach used in procedural languages like C, and it
hasnt worked very well. Like everything in Java, the solution
revolves around the class. You reuse code by creating new
classes, but instead of creating them from scratch, you use
existing classes that someone has already built and debugged.
COMPILED BY MICHAEL JONES

34

OOP I
Code Reuse Ways to accomplish
1. The trick is to use the classes without soiling the existing
code. The first way to accomplish this is quite
straightforward: you simply create objects of your existing
class inside the new class. This is called composition,
because the new class is composed of objects of existing
classes. Youre simply reusing the functionality of the code,
not its form.

COMPILED BY MICHAEL JONES

35

OOP I
Code Reuse Ways to accomplish
2. The second approach is more subtle. It creates a new class as
a type of an existing class. You literally take the form of the
existing class and add code to it without modifying the
existing class. This technique is called inheritance, and the
compiler does most of the work. Inheritance is one of the
cornerstones of object-oriented programming, and has
additional implications that will be explored later.

COMPILED BY MICHAEL JONES

36

OOP I
OOP Building Blocks - Encapsulation
There is a piece of wisdom which has made its way down
through centuries of software development..
Teams work best when members of those teams know as
little about each others' work as possible.
When one software module depends on the low-level
implementation details of another module, unexplained bugs
tend to appear as the system evolves.
The "back room" metaphor.
We need a way of not only suggesting that programmers stay
out of the "back room", but enforcing it.

COMPILED BY MICHAEL JONES

37

OOP I
OOP Building Blocks - Encapsulation
Encapsulation means that some or all of an object's internal
structure is "hidden" from the outside world.
Hidden information may only be accessed through the object's
methods, called the object's public interface.
Access to object is safe, controlled.
Methods, like instance variables, may also be hidden to create
private "helper functions".
Encapsulation provides abstraction
separates external view (behavior) from internal view (state)
COMPILED BY MICHAEL JONES

38

OOP I
OOP Building Blocks - Encapsulation

COMPILED BY MICHAEL JONES

39

OOP I
OOP Building Blocks - Encapsulation

COMPILED BY MICHAEL JONES

40

OOP I
OOP Building Blocks Encapsulation
Objects as goods and services

COMPILED BY MICHAEL JONES

41

OOP I
OOP Building Blocks Encapsulation
Encapsulation as maintainability

COMPILED BY MICHAEL JONES

42

OOP I
OOP Building Blocks - Encapsulation

COMPILED BY MICHAEL JONES

43

OOP I
OOP Building Blocks - Encapsulation

COMPILED BY MICHAEL JONES

44

OOP I
OOP Building Blocks - Encapsulation
To achieve encapsulation we use access specifiers to determine the
visibility of objects and data. There are three basic types:
1. Public public classes, methods, and fields can be accessed from
everywhere
2. Default (protected) - If you do not set access to a specific level,
then such a class, method, or field will be accessible from inside
the same package to which the class, method, or field belongs,
but not from outside the package.
COMPILED BY MICHAEL JONES

45

OOP I
OOP Building Blocks - Encapsulation
2. Protected protected methods and fields can only be accessed
within the same class to which the method and fields belong,
within its subclasses, and within classes of the same package.
3. Private private methods and fields can only be accessed within
the same class to which the methods and fields belong. Private
methods and fields are not visible within subclasses and are not
inherited by subclasses.

COMPILED BY MICHAEL JONES

46

OOP I
OOP Building Blocks Encapsulation Benefits
Provides abstraction between an object and its clients
Protects an object from unwanted access by clients.
A bank app forbids a client to change an Account's balance
Allows you to change the class implementation
Client still gets the account number but is not aware of the
underlying implementation
The users of a class do not know how the class stores its
data. A class can change the data type of a field and users
of the class do not need to change any of their code

COMPILED BY MICHAEL JONES

47

OOP I
OOP Building Blocks - Inheritance

COMPILED BY MICHAEL JONES

48

OOP I
OOP Building Blocks Inheritance
If class C is a subclass of class P, then C is a child class of P, and
P is a parent class or superclass of C. C inherits from P.
A child class automatically inherits all the structure and
functionality of its parent class. When defining a subclass, you
will usually choose to:
Add new instance variables and methods
Override some methods of the parent class, providing new
methods
In Java the extends keyword is used to create the parent child
relationship between classes
COMPILED BY MICHAEL JONES

49

OOP I
OOP Building Blocks Inheritance
Adding Structure/behaviour in subclasses

COMPILED BY MICHAEL JONES

50

OOP I
OOP Building Blocks Inheritance
Overriding behaviour in subclasses

COMPILED BY MICHAEL JONES

51

OOP I
OOP Building Blocks Inheritance
Overriding with default behaviour

COMPILED BY MICHAEL JONES

52

OOP I
OOP Building Blocks Inheritance hierarchy

COMPILED BY MICHAEL JONES

53

OOP I
OOP Building Blocks Inheritance schemes

COMPILED BY MICHAEL JONES

54

OOP I
OOP Building Blocks A single-inheritance class
hierarchy

COMPILED BY MICHAEL JONES

55

OOP I
OOP Building Blocks A single-inheritance scheme

COMPILED BY MICHAEL JONES

56

OOP I
OOP Building Blocks Inheritance Advantages of

COMPILED BY MICHAEL JONES

57

OOP I
OOP Building Blocks Abstraction
Abstract classes are classes which do not have instances of
their own: they cannot be instantiated. They exist solely so
that their child classes may inherit structure and/or
functionality.
Concrete classes are classes which may have instances. A
concrete class may also have child classes.

COMPILED BY MICHAEL JONES

58

OOP I
OOP Building Blocks Abstraction
You can declare an object without defining it:
Person p;

Similarly, you can declare a method without defining it:


public abstract void draw(int size);

Notice that the body of the method is missing


A method that has been declared but not defined is an
abstract method
Any class having one or more abstract methods must be
declared as abstract
COMPILED BY MICHAEL JONES

59

OOP I
OOP Building Blocks Abstraction
Any class containing an abstract method is an abstract class
You must declare the class with the keyword abstract:
abstract class MyClass {...}

An abstract class is incomplete


It has missing method bodies
You cannot instantiate (create a new instance of) an abstract
class

60

COMPILED BY MICHAEL JONES

OOP I
OOP Building Blocks Abstraction
You can extend (subclass) an abstract class
If the subclass defines all the inherited abstract methods, it
is complete and can be instantiated
If the subclass does not define all the inherited abstract
methods, it too must be abstract
You can declare a class to be abstract even if it does not
contain any abstract methods
This prevents the class from being instantiated
Abstract classes can have constructors and variables

61

COMPILED BY MICHAEL JONES

OOP I
OOP Building Blocks Why use Abstraction?

COMPILED BY MICHAEL JONES

62

OOP I

Interfaces
Interfaces in Java are special classes that are used to define
structure and/or functionality. Much like abstract classes,
interfaces only supply a method definition, but not an
implementation.
All the methods are implicitly public and abstract
You can add these qualifiers if you like, but why bother?
You cannot instantiate an interface
An interface is like a very abstract classnone of its
methods are defined
An interface may also contain constants (final variables)

63

COMPILED BY MICHAEL JONES

OOP I

Interfaces
Most of the time, you will use Sun-supplied Java interfaces.
Sometimes you will want to design your own
You would write an interface if you want classes of various
types to all have a certain set of capabilities
For example, if you want to be able to create animals that
speak human languages, you might define an interface as:
public interface SpeakingAnimal{
speak(String language);
}

Now you can write code that will create English speaking
animals, simply by calling these methods.
64

COMPILED BY MICHAEL JONES

OOP I

Interfaces
You extend a class, but you implement an interface
A class can only extend (subclass) one other class, but it can
implement as many interfaces as you like
Example:
class MyListener
implements KeyListener, ActionListener { }

Keep in mind any class implementing an interface must


implement all the abstract methods of the interface.

65

COMPILED BY MICHAEL JONES

OOP I

Interfaces
It is possible to define some but not all of the methods defined
in an interface:
abstract class MyKeyListener implements KeyListener
{
public void keyTyped(KeyEvent e) {...};
}

Since this class does not supply all the methods it has
promised, it is an abstract class
You must label it as such with the keyword abstract
You can even extend an interface (to add methods):
interface FunkyKeyListener extends KeyListener {
... }
66

COMPILED BY MICHAEL JONES

OOP I

OOP Building Blocks - Polymorphism


The term polymorphism literally means "having many forms"
A polymorphic reference is a variable that can refer to different
types of objects at different points in time
The method invoked through a polymorphic reference can
change from one invocation to the next
All object references in Java are potentially polymorphic

67

COMPILED BY MICHAEL JONES

OOP I

OOP Building Blocks - Polymorphism


When a program invokes a method through a superclass
variable,
the correct subclass version of the method is called,
based on the type of the reference stored in the superclass
variable
The same method name and signature can cause different
actions to occur,
depending on the type of object on which the method is
invoked

COMPILED BY MICHAEL JONES

68

OOP I

OOP Building Blocks - Polymorphism


Polymorphism enables programmers to deal in generalities
and
let the execution-time environment handle the specifics.
Programmers can command objects to behave in manners
appropriate to those objects,
without knowing the types of the objects
(as long as the objects belong to the same inheritance
hierarchy).

COMPILED BY MICHAEL JONES

69

OOP I
OOP Building Blocks Polymorphism
Promoting Extensibility
Software that invokes polymorphic behavior
independent of the object types to which messages are
sent.
New object types that can respond to existing method calls
can be
incorporated into a system without requiring modification
of the base system.
Only client code that instantiates new objects must be
modified to accommodate new types.

COMPILED BY MICHAEL JONES

70

OOP I

OOP Building Blocks Polymorphism

COMPILED BY MICHAEL JONES

71

OOP I

OOP Building Blocks Polymorphism

COMPILED BY MICHAEL JONES

72

OOP I

Variable Scope
A class can contain any of the following variable types:
1.

Local variables: Variables defined inside methods, constructors or


blocks are called local variables. The variable will be declared and
initialized within the method and the variable will be destroyed
when the method has completed (at the end of its execution)

2.

Instance variables: Instance variables are variables defined within


a class but outside any method. These variables are instantiated
when the class is loaded. Instance variables can be accessed from
inside any method, constructor or blocks of that particular class
COMPILED BY MICHAEL JONES

73

OOP I

Variable Scope
3. Parameter Variables: A parameter variable is used to
store information that is being passed from the location of
the method call into the method that is called. Parameter
variables has no visibility outside of the methods that they
were defined. The are e

COMPILED BY MICHAEL JONES

74

OOP I

Keywords - this
this is an alias or a name for the current instance inside
the instance
It is useful for disambiguating instance variables from
locals (including parameters), but it can be used by itself
to simply:
refer to member variables and methods
invoke other constructor overloads, or
simply to refer to the instance

COMPILED BY MICHAEL JONES

75

OOP I

Keywords - super
The super keyword in java is a reference variable that is used
to refer immediate parent class object. Whenever you create
the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable.
Usage of java super Keyword:
super is used to refer immediate parent class instance
variable
super() is used to invoke immediate parent class
constructor.
super is used to invoke immediate parent class
method.
COMPILED BY MICHAEL JONES

76

OOP I

Keywords instanceof
instanceof is a keyword that tells you whether a variable is a
member of a class or interface. For example, if
class Dog extends Animal implements Pet {...}
Animal fido = new Dog();

then the following are all true:


fido instanceof Dog
fido instanceof Animal
fido instanceof Pet
instanceof is seldom used
When you find yourself wanting to use instanceof, think about whether
the method you are writing should be moved to the individual
subclasses
77

COMPILED BY MICHAEL JONES

Vous aimerez peut-être aussi