We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8
Data/Information Hiding,
Encapsulation
Lecture 7
Asif Shahzad, Assistant Professor
COMSATS University Islamabad, Lahore Campus Private Behavior and Attributes of object • Our home is an object, its kitchen and bedroom are private. We do not allow guests or strangers to visit our kitchen and bedrooms. • In same way, mobile number is our attribute, but we do not share it with everyone. It’s our private attribute. • We do not allow others access or call our certain behavior e.g. shopping and eating. • In same way, an automatic car do not allow the driver to change its gear, it changes it automatically. Use Access Modifiers: public or private • We can make certain behavior private, by declaring it with ‘private’ access modifier. Example, hide calculateAverage() • In same way, to make an attribute hidden from outside world, declare it as private e.g. mobileNumber.
• Other classes, where object of our class is created, would not
be able to read/call private attributes/methods. Private attributes and methods are accessible within the class. Encapsulation 1. Lets say, we want Student id be a positive integer. How to do it? Demo.. 2. So, to encapsulate a field, we can make it private and create public get and set methods to give read/write access of attribute to others. 3. In object oriented design, its Student class responsibility to make sure, it will always store a valid id. 4. So encapsulation help to prevent data corruption by other objects / entities. Why we declare an attribute as private? • Why we declare an attribute as private? • To ensure data validity • To enforce some organization constraints at write and read opration • To have some private state which other objects has no concern Conventions About get/set methods • Method name is prefixed with ‘get’ or ‘set’ followed by attribute name (use camel notation for methods). • The get method's return type must be the type of attribute it returns and it must not receive any argument. • The set method's return type is always void and it must receive only one argument whose type must be same as the type of the attribute being set. • Access modifier for the get and set methods is generally public, but its not a requirement or convention. It can be changed as per application requirements. Next ! How we can initialize state at the time of object construction?