The principles of object-oriented programming
Object-oriented programming (OOP)
A programming model that focuses on an application’s components and data and the
methods to manipulate them
Uses all of the familiar concepts from modular procedural programming
Variables, methods, passing arguments
Sequence, selection, and looping structures
But involves a different way of thinking
Important features of object-oriented languages
Classes
Objects
Polymorphism
Inheritance
Encapsulation
Classes
Class
Describes a group or collection of objects with common attributes
Object - One instance of a class
Sometimes called one instantiation of a class
When a program creates an object, it instantiates the object
Example
Class name: dog
Attributes: name, age, hasShots
Methods: changeName, updateShots
Attributes
Characteristics that define an object as part of a class
Example
Automobile’s attributes: make, model, year, and purchase price
Methods
Actions that alter, use, or retrieve the attributes
Example
Methods for changing an automobile’s running status, gear, speed, and cleanliness
Think in an object-oriented manner
Everything is an object
Every object is a member of a class
Is-a relationship
, “My oak desk with the scratch on top is a Desk”
Class reusability
Class’s instance variables
Data components of a class that belong to every instantiated object
Often called fields
State
A set of all the values or contents of a class object’s instance variables
Every object that is an instance of a class possesses the same methods
Create classes from which objects will be instantiated
Class client or class user
A program or class that instantiates objects of another prewritten class
Polymorphism
The world is full of objects
A door is an object that needs to be open or closed
But an “open” procedure works differently on different objects
Open a door
Open a drawer
Open a bank account
Open a file
Open your eyes
One “open” procedure can open anything if it gets the correct arguments
Inheritance
Inheritance
The process of acquiring the traits of one’s predecessors
Example
A door with a stained-glass window inherits all the attributes (doorknob, hinges) and
methods (open and close) of a door
Once you create an object
Develop new objects that possess all the traits of the original object
Plus, new traits
Encapsulation
Encapsulation
The process of combining all of an object’s attributes and methods into a single package
Information hiding (also called data hiding)
Other classes should not alter an object’s attributes
Outside classes should only be allowed to make a request that an attribute be altered
It is up to the class’s methods to determine whether the request is appropriate