SlideShare a Scribd company logo
1 of 21
ENCAPSULATION
Michael Heron
Introduction
• One of the greatest tools available in object orientation for
the design of clean programs is encapsulation.
• Some writers make a distinction between encapsulation
and data hiding.
• I don’t find this to be a useful distinction, so we won’t be focusing
on it particularly.
• Just know that some of the things I talk about may have different
names if you read up on them elsewhere.
Encapsulation
• Encapsulation is the technique of storing data alongside
the methods that act upon that data.
• Sounds trivial, but it was a paradigm shift at the time.
• Objects provide a natural way of encapsulating data and
attributes.
• Objects also provide a way of managing access to those
data elements and attributes.
Encapsulation and the Impact of Change
• When used well, encapsulation greatly reduces the
impact of change in an application.
• By treating objects as atomic, it’s possible to swap them in
and out as possible.
• It’s also possible, if they are well designed, to refactor
them without any impact on the rest of the application.
Information Hiding
• One of the things that encapsulation permits is the
restriction of access to attributes and methods.
• This done through the use of visibility modifiers.
• There are three basic visibility modifiers common to Java
and C++
• Private
• Protected
• Public
Private
• Private indicates that visibility is restricted to the object in
which the item is defined.
• It is not available to external objects.
• It is not available to objects that extend the object.
• It is the most restrictive level of access.
• All attributes in a class should be private unless actively required to
be otherwise.
• It has the lowest impact of change.
• Refactoring can be limited to the class itself.
Protected
• Protected means that the class in which the item is
defined and any children of that class can get access.
• It’s not available to external objects.
• Any child that is specialised from, at some point, the class in which
the item is defined has access.
• Limits the impact of change to the defining class and
specialisations only.
• Refactoring can be limited to these classes.
Public
• The greatest level of visibility.
• Every object has access.
• Public methods that provide access to private attributes
are a good example of the utility of public methods.
• Accessor methods, as they are known.
• Greatest impact of change.
• You have to assume if something can be used, it is being used.
• Scope of refactoring becomes the entire program.
Why Hide Information?
• Simplify documentation.
• External documentation can focus on only relevant functions.
• Can ensure fidelity of access.
• If the only access to data is through methods you provide, you can
ensure consistency of access.
• Hides the implementation details from other objects.
• In large projects, a developer should not have to be aware of how a
class is structures.
• Simplifies code
• All access to the object through predefined interfaces.
Problems with Information Hiding
• They are conventions that have been adopted.
• You can’t guarantee they are being adhered to.
• Can lead to duplication of effort or over-engineering of
code solutions.
• Can lead to security leaks as people attempt to work
around restrictions.
• Especially a problem when working with pointers and object
references.
Encapsulation in C++
• So far, the concept is identical in C++ and Java.
• C++ offers an additional facility for defining visibility.
• The friend relationship.
• Friends have access to private attributes and methods
• We define specific classes as having friend access to our class.
Friends Will Be Friends
• We have two ways of defining a friend relationship.
• We can define a function as having friend access.
• We can define a class as having friend access.
• The first permits us to write our own implementation of a
method to access a private data attribute.
• Not a good idea.
• It breaks encapsulation.
• The second permits us to name a class as having
privileged access.
• Useful in certain limited circumstances.
• I’m told.
Friends Will Be Friends
using namespace std;
class Car {
friend class TestClass;
private:
float price;
string colour;
string *owners;
int max_size;
int current_size;
public:
Car();
Car (float, string = "bright green");
Car (float, string = "bright green", int = 20);
~Car();
void set_price (float p);
float query_price();
void set_colour (string c);
string query_colour();
string to_string();
int query_size();
int query_current_size();
void add_owner (string str);
string query_owner (int ind);
};
Friends Will Be Friends
class TestClass {
public:
void modify_price (Car *c, float f);
};
void TestClass::modify_price (Car *car, float x) {
car->price = x;
}
int main() {
ExtendedCar *myCar;
TestClass *bing
myCar = new ExtendedCar (100.0, "black", 10, 50.0);
bing = new TestClass();
bing->modify_price (myCar, 150.0);
cout << myCar->query_price () << endl;
return 1;
}
Friend Classes
• There are some caveats to using Friend relationships.
• The permission does not extend to derived classes.
• The permission is not reciprocated.
• If A is a friend of B, it doesn’t follow that B is a friend of A
• The permission is not transitive.
• Friends of friends are not friends.
Designing A Class
• A properly encapsulated class has the following traits.
• All data that belongs to the class is stored in the class.
• Or at least, represented directly in the class.
• All attributes are private.
• There’s almost never a good reason to make an attribute public.
• Hardly ever a good reason to make an attribute protected.
The Class Interface
• Classes have a defined interface.
• This is the set of public methods they expose.
• A properly encapsulated class has a coherent interface.
• It exposes only those methods that are of interest to external
classes.
• A properly encapsulated class has a clean divide between
its interface and its implementation.
Interfaces
• The easiest way to think of an interface is with a metaphor.
• Imagine your car’s engine.
• You don’t directly interact with the engine.
• You have an interface to that car engine that is defined by:
• Gears
• Pedals
• Ignition
• Likewise with the car wheels.
• Your steering wheel is the interface to your wheels.
• As long as the interface remains consistent…
• It doesn’t matter what engine is in the car.
• Change the interface, and you can no longer drive the car the same way.
Interface and Implementation
• Within a properly encapsulated class, it does not matter to
external developers how a class is implemented.
• I know what goes in
• I know what comes out
• The interface to a class can remain constant even while
the entirety of the class is rewritten.
• Not an uncommon act in development.
Interface and Implementation
• It’s important to design a clean an effective interface.
• It’s safe to change encapsulated implementation.
• It’s usually not safe to change a public interface.
• You are committed to the code that you expose publicly.
• When new versions of Java deprecate existing functionality, they
never just switch it off.
Summary
• Encapsulation is the third of the three key principles of
object orientation.
• It is properly broken up into two separate concepts.
• Encapsulation and Information Hiding
• Visibility modifiers exist to restrict access to objects.
• C++ (not Java) makes available a special relationship
known as a friend relationship.

More Related Content

What's hot

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 

What's hot (20)

Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Characteristics of OOPS
Characteristics of OOPS Characteristics of OOPS
Characteristics of OOPS
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
C# Encapsulation
C# EncapsulationC# Encapsulation
C# Encapsulation
 
Java packages
Java packagesJava packages
Java packages
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
OOP C++
OOP C++OOP C++
OOP C++
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 

Viewers also liked

Osi reference model
Osi reference modelOsi reference model
Osi reference model
prashob7
 

Viewers also liked (20)

Flavor encapsulation assignment
Flavor encapsulation assignmentFlavor encapsulation assignment
Flavor encapsulation assignment
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Encapsulation in JavaScript - OOP
Encapsulation in JavaScript - OOPEncapsulation in JavaScript - OOP
Encapsulation in JavaScript - OOP
 
CPP14 - Encapsulation
CPP14 - EncapsulationCPP14 - Encapsulation
CPP14 - Encapsulation
 
Applications of extrusion in encapsulation technology
Applications of extrusion in encapsulation technologyApplications of extrusion in encapsulation technology
Applications of extrusion in encapsulation technology
 
Iso osi
Iso osiIso osi
Iso osi
 
Modem
ModemModem
Modem
 
wireless networks
wireless networkswireless networks
wireless networks
 
Process Analysis
Process AnalysisProcess Analysis
Process Analysis
 
DISE - OOAD Using UML
DISE - OOAD Using UMLDISE - OOAD Using UML
DISE - OOAD Using UML
 
Repeaters.51
Repeaters.51Repeaters.51
Repeaters.51
 
OSI reference model
OSI reference modelOSI reference model
OSI reference model
 
Repeater
Repeater Repeater
Repeater
 
Osi reference model
Osi reference modelOsi reference model
Osi reference model
 
Network Interface Card (NIC) AND NETWORKING DEVICES
Network Interface Card (NIC) AND NETWORKING DEVICESNetwork Interface Card (NIC) AND NETWORKING DEVICES
Network Interface Card (NIC) AND NETWORKING DEVICES
 
Communication Models
Communication ModelsCommunication Models
Communication Models
 
Network Devices
Network DevicesNetwork Devices
Network Devices
 
ISO OSI Model
ISO OSI ModelISO OSI Model
ISO OSI Model
 
Communication Process, Its Elements & Models By Shisupal Jat & Bhim Sain
Communication Process, Its Elements & Models By Shisupal Jat & Bhim SainCommunication Process, Its Elements & Models By Shisupal Jat & Bhim Sain
Communication Process, Its Elements & Models By Shisupal Jat & Bhim Sain
 

Similar to 2CPP09 - Encapsulation

Similar to 2CPP09 - Encapsulation (20)

UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program2CPP05 - Modelling an Object Oriented Program
2CPP05 - Modelling an Object Oriented Program
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
Improving Software Quality Using Object Oriented Design Principles
Improving Software Quality Using Object Oriented Design PrinciplesImproving Software Quality Using Object Oriented Design Principles
Improving Software Quality Using Object Oriented Design Principles
 
80410172053.pdf
80410172053.pdf80410172053.pdf
80410172053.pdf
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Core Java for Selenium
Core Java for SeleniumCore Java for Selenium
Core Java for Selenium
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx
 
CPP16 - Object Design
CPP16 - Object DesignCPP16 - Object Design
CPP16 - Object Design
 

More from Michael Heron

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 

2CPP09 - Encapsulation

  • 2. Introduction • One of the greatest tools available in object orientation for the design of clean programs is encapsulation. • Some writers make a distinction between encapsulation and data hiding. • I don’t find this to be a useful distinction, so we won’t be focusing on it particularly. • Just know that some of the things I talk about may have different names if you read up on them elsewhere.
  • 3. Encapsulation • Encapsulation is the technique of storing data alongside the methods that act upon that data. • Sounds trivial, but it was a paradigm shift at the time. • Objects provide a natural way of encapsulating data and attributes. • Objects also provide a way of managing access to those data elements and attributes.
  • 4. Encapsulation and the Impact of Change • When used well, encapsulation greatly reduces the impact of change in an application. • By treating objects as atomic, it’s possible to swap them in and out as possible. • It’s also possible, if they are well designed, to refactor them without any impact on the rest of the application.
  • 5. Information Hiding • One of the things that encapsulation permits is the restriction of access to attributes and methods. • This done through the use of visibility modifiers. • There are three basic visibility modifiers common to Java and C++ • Private • Protected • Public
  • 6. Private • Private indicates that visibility is restricted to the object in which the item is defined. • It is not available to external objects. • It is not available to objects that extend the object. • It is the most restrictive level of access. • All attributes in a class should be private unless actively required to be otherwise. • It has the lowest impact of change. • Refactoring can be limited to the class itself.
  • 7. Protected • Protected means that the class in which the item is defined and any children of that class can get access. • It’s not available to external objects. • Any child that is specialised from, at some point, the class in which the item is defined has access. • Limits the impact of change to the defining class and specialisations only. • Refactoring can be limited to these classes.
  • 8. Public • The greatest level of visibility. • Every object has access. • Public methods that provide access to private attributes are a good example of the utility of public methods. • Accessor methods, as they are known. • Greatest impact of change. • You have to assume if something can be used, it is being used. • Scope of refactoring becomes the entire program.
  • 9. Why Hide Information? • Simplify documentation. • External documentation can focus on only relevant functions. • Can ensure fidelity of access. • If the only access to data is through methods you provide, you can ensure consistency of access. • Hides the implementation details from other objects. • In large projects, a developer should not have to be aware of how a class is structures. • Simplifies code • All access to the object through predefined interfaces.
  • 10. Problems with Information Hiding • They are conventions that have been adopted. • You can’t guarantee they are being adhered to. • Can lead to duplication of effort or over-engineering of code solutions. • Can lead to security leaks as people attempt to work around restrictions. • Especially a problem when working with pointers and object references.
  • 11. Encapsulation in C++ • So far, the concept is identical in C++ and Java. • C++ offers an additional facility for defining visibility. • The friend relationship. • Friends have access to private attributes and methods • We define specific classes as having friend access to our class.
  • 12. Friends Will Be Friends • We have two ways of defining a friend relationship. • We can define a function as having friend access. • We can define a class as having friend access. • The first permits us to write our own implementation of a method to access a private data attribute. • Not a good idea. • It breaks encapsulation. • The second permits us to name a class as having privileged access. • Useful in certain limited circumstances. • I’m told.
  • 13. Friends Will Be Friends using namespace std; class Car { friend class TestClass; private: float price; string colour; string *owners; int max_size; int current_size; public: Car(); Car (float, string = "bright green"); Car (float, string = "bright green", int = 20); ~Car(); void set_price (float p); float query_price(); void set_colour (string c); string query_colour(); string to_string(); int query_size(); int query_current_size(); void add_owner (string str); string query_owner (int ind); };
  • 14. Friends Will Be Friends class TestClass { public: void modify_price (Car *c, float f); }; void TestClass::modify_price (Car *car, float x) { car->price = x; } int main() { ExtendedCar *myCar; TestClass *bing myCar = new ExtendedCar (100.0, "black", 10, 50.0); bing = new TestClass(); bing->modify_price (myCar, 150.0); cout << myCar->query_price () << endl; return 1; }
  • 15. Friend Classes • There are some caveats to using Friend relationships. • The permission does not extend to derived classes. • The permission is not reciprocated. • If A is a friend of B, it doesn’t follow that B is a friend of A • The permission is not transitive. • Friends of friends are not friends.
  • 16. Designing A Class • A properly encapsulated class has the following traits. • All data that belongs to the class is stored in the class. • Or at least, represented directly in the class. • All attributes are private. • There’s almost never a good reason to make an attribute public. • Hardly ever a good reason to make an attribute protected.
  • 17. The Class Interface • Classes have a defined interface. • This is the set of public methods they expose. • A properly encapsulated class has a coherent interface. • It exposes only those methods that are of interest to external classes. • A properly encapsulated class has a clean divide between its interface and its implementation.
  • 18. Interfaces • The easiest way to think of an interface is with a metaphor. • Imagine your car’s engine. • You don’t directly interact with the engine. • You have an interface to that car engine that is defined by: • Gears • Pedals • Ignition • Likewise with the car wheels. • Your steering wheel is the interface to your wheels. • As long as the interface remains consistent… • It doesn’t matter what engine is in the car. • Change the interface, and you can no longer drive the car the same way.
  • 19. Interface and Implementation • Within a properly encapsulated class, it does not matter to external developers how a class is implemented. • I know what goes in • I know what comes out • The interface to a class can remain constant even while the entirety of the class is rewritten. • Not an uncommon act in development.
  • 20. Interface and Implementation • It’s important to design a clean an effective interface. • It’s safe to change encapsulated implementation. • It’s usually not safe to change a public interface. • You are committed to the code that you expose publicly. • When new versions of Java deprecate existing functionality, they never just switch it off.
  • 21. Summary • Encapsulation is the third of the three key principles of object orientation. • It is properly broken up into two separate concepts. • Encapsulation and Information Hiding • Visibility modifiers exist to restrict access to objects. • C++ (not Java) makes available a special relationship known as a friend relationship.