Object Oriented Programming
Object Oriented Programming
and Java
2
OOP Facilitates
• Reusing the existing code
• Keep data near the significant code.
• Provide a nice wrapping mechanism for
related code.
• Model the world as objects.
• objects can send "messages" to each other.
3
An Object
• Collection of: real world entities such as
– object state, data members, instance variables.
– Methods
– Each object has it's own memory for
maintaining state
– All objects of the same type share code.
4
OOP Benefits
• Code re-use
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• And message communication
5
Code Re-Use
• nice packaging makes it easy to document/find
appropriate code.
6
Encapsulation
• Information Hiding.
• Implementation can change without
effecting any calling code.
• "keeps us from ourselves"
7
Inheritance
• Properties of one class may be shared with
another i.e. a code re-use issue.
– we can extend code that is already written in a
wide range.
• Inheritance is more, it supports
polymorphism at the language level!
8
Example of inheritance
• Employee: name, email, phone
– FulltimeEmployee:
also has salary, office, benefits, …
9
Polymorphism
• Generally, the ability to appear in many
forms. In object-oriented programming,
polymorphism refers to a programming
language's ability to process objects
differently depending on their data type or
class. More specifically, it is the ability to
redefine methods for derived classes.
10
Method Polymorphism
• The real power comes with
methods/behaviors.
• A better example:
– shape object types used by a drawing program.
– we want to be able to handle any kind of shape
someone wants to code (in the future).
– we want to be able to write code now that can
deal with shape objects (without knowing what
they are!).
11
Shapes
• Shape:
– color, layer fields
12
Java OOP
• Create new object type with class keyword.
• A class definition can contain:
– variables (fields)
– initialization code
– methods
13
class definition
class classname {
field declarations
{ initialization code }
Constructors
Methods
}
14
Creating an Object
• Defining a class does not create an object of
that class - this needs to happen explicitly:
classname varname = new classname();
15
The class Object
• It is most important of all Java classes.
16