Object Based Programming - Complete
Object Based Programming - Complete
OOP I
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.
OOP I
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...
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
Classes
Encapsulation
Instance Variables
Inheritance
Abstraction
Polymorphism
Class variables/methods
Variable Scope
Types of Methods
Common keywords
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?
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.
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
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.
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:
17
OOP I
What messages look like
A message generally has three parts:
The receiver: the object receiving the message.
18
OOP I
What methods look like
19
OOP I
An OO bestiary
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.
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).
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)
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
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.
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.
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
29
OOP I
Creating and Using Objects
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
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
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.
32
OOP I
Composition
Composition defines a HAS A relationship.
class Engine {}
class Car{
// Cars have engines so, Car class has an instance of
//Engine class as its member.
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.
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.
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.
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
39
OOP I
OOP Building Blocks - Encapsulation
40
OOP I
OOP Building Blocks Encapsulation
Objects as goods and services
41
OOP I
OOP Building Blocks Encapsulation
Encapsulation as maintainability
42
OOP I
OOP Building Blocks - Encapsulation
43
OOP I
OOP Building Blocks - Encapsulation
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.
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
47
OOP I
OOP Building Blocks - Inheritance
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
50
OOP I
OOP Building Blocks Inheritance
Overriding behaviour in subclasses
51
OOP I
OOP Building Blocks Inheritance
Overriding with default behaviour
52
OOP I
OOP Building Blocks Inheritance hierarchy
53
OOP I
OOP Building Blocks Inheritance schemes
54
OOP I
OOP Building Blocks A single-inheritance class
hierarchy
55
OOP I
OOP Building Blocks A single-inheritance scheme
56
OOP I
OOP Building Blocks Inheritance Advantages of
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.
58
OOP I
OOP Building Blocks Abstraction
You can declare an object without defining it:
Person p;
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 {...}
60
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
OOP I
OOP Building Blocks Why use Abstraction?
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
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
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 { }
65
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
OOP I
67
OOP I
68
OOP I
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.
70
OOP I
71
OOP I
72
OOP I
Variable Scope
A class can contain any of the following variable types:
1.
2.
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
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
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();