Sei sulla pagina 1di 12

Encapsulation

Ata-ur-Rahman FA17-MCS-033

Umair Alam FA17-MCS-028


Contents

❖ Introduction
❖ Importance
❖ Why need Encapsulation
❖ Example

2
INTRODUCTION

❑ Encapsulation is the technique of making


the fields in a class private and providing
access to the fields via public methods.
❑ Encapsulation also can be described as a
protective barrier that prevents the code
and data being randomly accessed by other
code defined outside the class.
3
IMPORTANCE

❑ To hide the internal implementation details


of the class.
❑ Can safely modified the implementation
without worrying breaking the existing code
that uses the class.
❑ Easier to use and understand.
4
WHY NEED ENCAPSULATION

❑ Combining data and how it's manipulated in


one place: This is achieved through the state
(the private fields) and the behaviors (the
public methods) of an object.
❑ Only allowing the state of an object to be
accessed and modified through behaviors:
The values contained within an object's state
can then be strictly controlled. 5
EXAMPLE

class college void display() {


{ System.out.println(“Code is:
”+ccode+” & Name is: ”+cname);
private int ccode; }
private String cname; }

void get(int x, String y) { public class mainclass {


ccode = x; public static void main (String args[])
cname = y; { college c = new college();
} c.get(123,Ali);
c.display(); }
} 6
Contents

❖ Benefits
➢ Maintainability
➢ Flexibility
➢ Extensibility
❖ Visibility Modifiers
❖ Example

7
BENEFITS

➢ Total control over fields.


➢ The fields of a class can be made read-only
or write- only.
➢ Modify the code without effecting the code
of others.
➢ Maintainability, Flexibility and Extensibility.
8
BENEFITS (Contd.)

Maintainability: It provides a boundary around a


set of data and methods. Allows using the code
without knowing how it works.
Flexibility: Easier to visualize.
Extensibility: Makes long term development
easy. Code can be implemented Changing
without effecting the input and output formats.
9
VISIBILITY MODIFIERS

❖ Determines which class members are accessible and


which are not.
▪ Public : can be accessed from outside of the class
definition.
▪ Package(Friendly): can be accessed anywhere within the
same package.
▪ Protected : can be accessed only within the same class
definition and the definition of subclasses.
▪ Private : can be accessed only within the same class
definition. 10
EXAMPLE

11
THANKS!
Any questions?

12

Potrebbero piacerti anche