SlideShare a Scribd company logo
1 of 26
08 Encapsulation and Abstraction
2
Contents
• Defining Abstraction
• Levels of Abstraction
• Class as Abstraction
• Defining a Java Class
• Instantiating a Class
• Class Members
• Class Modifiers
• Member Modifiers
• Accessibility Scope
• Defining Encapsulation
• Principles of
Encapsulation
• Encapsulating a Class
• Setters & Getters
• Constructors
3
Objectives
• Define abstraction
• Identify levels of abstraction
• Understand that a class is a form of abstraction
• Define a Java class
• Learn how to create objects by instantiating their class
• Identify class members
• Identify and define each modifier applicable to a class
• Identify and define each modifier applicable to class
members
• Define access scope for class and its members
• Know the purpose of constructors and how to create one
for a class
4
Objectives (continued)
• Define encapsulation
• Describe the principles of encapsulation
• Learn how to encapsulate a class
• Learn how to use setters and getters
5
Defining Abstraction
• Abstraction is the process of extracting common features
from specific examples
• Abstraction is a process of defining the essential concepts
while ignoring the inessential details
6
Different Types of Abstraction
• Data Abstraction
Programming languages define constructs to simplify the
way information is presented to the programmer.
• Functional Abstraction
Programming languages have constructs that ‘gift wrap’
very complex and low level instructions into instructions
that are much more readable.
• Object Abstraction
OOP languages take the concept even further and
abstract programming constructs as objects.
7
Anything that you can describe can be represented
as an object, and that representation can be created,
manipulated and destroyed to represent how you use
the real object that it models.
Everything is an Object
8
An object is a self-contained entity
with attributes and behaviors
Defining an Object
information an object must know:
 identity – uniqueness
 attributes – structure
 state – current condition
behavior an object must do:
 methods – what it can do
 events – what it responds to
9
Class as Abstraction
• A class is an abstraction of its
instances. It defines all the
attributes and methods that its
instances must also have.
Person
name
sex
age
tellSex()
tellAge()
10
• A Class acts as the template from which an instance of an
object is created. The class defines the properties of the
object and the methods used to control the object's
behavior.
• A Class specifies the structure of data as well as the
methods which manipulate that data. Such data and
methods are contained in each instance of the class.
• A Class is a model or template that can be instantiated to
create objects with a common definition, and therefore
common properties, operations and behavior.
• A Class provides a template for defining the behavior of a
particular type of object. Objects are referred to as
“instances” of a class.
Defining a Class
11
Defining a Java Class
• A Java Class denotes a category of objects, and acts as a blueprint for creating
such objects.
• It defines its members referred to as fields and methods.
• The fields (also known as variables or attributes) refer to the properties of the
class.
• The methods (also known as operations) refer to behaviors that the class
exhibits.
class Person {
String name;
char sex;
int age;
void tellSex() {
if (sex=='M')
System.out.println("I'm Male.");
else if (sex=='F')
System.out.println("I'm Female.");
else System.out.println("I don't know!");
}
void tellAge() {
if (age<10)
System.out.println("I'm just a kid.");
else if (age<20)
System.out.println("I'm a teenager.");
else System.out.println("I'm a grown up.");
}
}
12
Class Members
• A class member refers to one of the fields or methods of a class.
• Static members are variables and methods belonging to a class where only a single copy
of variables and methods are shared by each object.
• Instance members are variables and methods belonging to objects where a copy of each
variable and method is created for each object instantiated.
class Person {
static int maleCount;
static int femaleCount;
String name;
char sex;
int age;
static void showSexDistribution() {
if (maleCount>femaleCount)
System.out.println("Majority are male.");
else if (femaleCount>maleCount)
System.out.println("Majority are female.");
else System.out.println("Equal number of male and female.");
}
void tellSex() {
if (sex=='M')
System.out.println("I'm Male.");
else if (sex=='F')
System.out.println("I'm Female.");
else System.out.println("I don't know!");
}
void tellAge() {
if (age<10)
System.out.println("I'm just a kid.");
else if (age<20)
System.out.println("I'm a teenager.");
else System.out.println("I'm a grown up.");
}
}
13
class Person {
static int maleCount;
static int femaleCount;
String name;
char sex;
int age;
static void showSexDistribution() {
// method body here
}
void tellSex() {
// method body here
}
void tellAge() {
// method body here
}
}
Instantiating a Class &
Accessing its Members
Access class variables
by setting their values
• Instantiating a class means creating objects of its own type.
• The new operator is used to instantiate a class.
class MainProgram {
public static void main(String[] args) {
// instantiating several objects
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
// accessing instance variables
p1.name = "Vincent"; p1.sex = 'M'; p1.age = 8;
p2.name = "Janice"; p2.sex = 'F'; p2.age = 19;
p3.name = "Ricky"; p3.sex = 'M'; p3.age = 34;
// accessing static variables
Person.maleCount = 2;
Person.femaleCount = 1;
// accesssing instance methods
p1.tellSex(); p1.tellAge();
p2.tellSex(); p2.tellAge();
p3.tellSex(); p3.tellAge();
// accessing static method
Person.showSexDistribution();
}
}
Access class methods
by invoking their names
Create Person objects
using the new operator.
Sample Output:
I'm Male.
I'm just a kid.
I'm Female.
I'm a teenager.
I'm Male.
I'm a grown up.
Majority are male.
14
Class Modifiers
Modifier Description
(no modifier) class is accessible within its package only
public class is accessible by any class in any package
abstract class cannot be instantiated (a class cannot be
abstract and final at the same time)
final class cannot be extended
strictfp class implements strict floating-point arithmetic
• Class modifiers change the way a class can be used.
• Access modifiers describe how a class can be accessed.
• Non-access modifiers describe how a class can be manipulated.
15
Access Modifiers
Modifier Description
(no
modifier)
member is accessible within its package only
public member is accessible from any class of any
package
protected member is accessible in its class package and by
its subclasses
private member is accessible only from its class
• Member modifiers change the way class members can be used
• Access modifiers describe how a member can be accessed
16
Sample
Package
ClassClass
Class
Class
Private features of the
Sample class can only be
accessed from within the
class itself.
Private features of the
Sample class can only be
accessed from within the
class itself.
private
Classes that are in the
package and all its
subclasses may access
protected features of the
Sample class.
Classes that are in the
package and all its
subclasses may access
protected features of the
Sample class.
protected
Only classes that are in the
package may access
default features of classes
that are in the package
Only classes that are in the
package may access
default features of classes
that are in the package
default
All classes may access
public features of the
Sample class.
All classes may access
public features of the
Sample class.
public
Class
Class
* Default is not a modifier; it is just the name of the access level if no access modifier is specified.
Access Modifiers
17
Member Modifiers
• Member modifiers change the way class members can be used
• Non-access modifiers describe how a member can be manipulated
Modifier Description
static member belongs to a class
final declares a constant variable or method
abstract method is declared with no implementation (applied to methods, cannot
be combined with other non-access modifiers )
strictfp method implements strict floating-point arithmetic (applied to methods)
synchronized method is executed by only one thread at a time (applied only to
methods)
native method implementation is written in other language (applied only to
methods)
transient an instance variable is not saved when its object is persisted or
serialized (applied only to variables)
volatile variable is modified asynchronously by concurrently running threads
(applied only to variables)
18
Accessibility Scope
Scope Access
static static code can access static members but not instance
members
non-static non-static code can access both static members and
instance members
package a class and its members can be accessed within the
package they are declared
class class members can be accessed within the class
block local variables can be accessed only within a block
• Accessibility scope defines the boundary of access to a
class and its members
19
Defining Encapsulation
• Encapsulation is the process of hiding an
object’s implementation from another
object, while presenting only the interfaces
that should be visible.
20
Principles of Encapsulation
“Don’t ask how I do it, but this is what I
can do”
- The encapsulated object
“I don’t care how, just do your job, and I’ll
do mine”
- One encapsulated object to another
21
Encapsulating a Class
• Members of a class must always be declared with the
minimum level of visibility.
• Provide setters and getters (also known as
accessors/mutators) to allow controlled access to private
data.
• Provide other public methods (known as interfaces ) that
other objects must adhere to in order to interact with the
object.
22
Setters and Getters
private char sex;
public void setSex(char s) {
// validate here
sex = s;
}
public char getSex() {
// format here
return sex;
}
• Setters and Getters allow controlled access to class data
• Setters are methods that (only) alter the state of an object
• Use setters to validate data before changing the object
state
• Getters are methods that (only) return information about the
state of an object
• Use getters to format data before returning the object’s
state
23
Encapsulation Example
public static void main(String[] args) {
// instantiate several objects
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
// access instance variables using setters
p1.setName("Vincent"); p1.setSex('M');
p1.setAge(8);
p2.setName("Janice"); p2.setSex('F');
p1.setAge(19);
p3.setName("Ricky"); p3.setSex('M');
p3.setAge(34);
// access static variables directly
Person.maleCount=2;
Person.femaleCount=1;
// access instance methods
p1.tellSex(); p1.tellAge();
p2.tellSex(); p2.tellAge();
p3.tellSex(); p3.tellAge();
// access static method
Person.showSexDistribution();
}
class Person {
// set variables to private
private static int maleCount;
private static int femaleCount;
private String name;
private char sex;
private int age;
/*
* setters & getters, set to public
*/
public int getAge() { return age;}
public void setAge(int a) { age = a;}
public String getName() { return name;}
public void setName(String n) { name = n;}
public char getSex() { return sex;}
public void setSex(char s) { sex = s;}
/*
* set other methods as interfaces
*/
public static void showSexDistribution() {
// implementation here
}
public void tellSex() {
// implementation here
}
public void tellAge() {
// implementation here
}
}
I'm Male.
I'm just a kid.
I'm Female.
I'm a teenager.
I'm Male.
I'm a grown up.
Majority are male.
24
Constructors
• Constructors are methods which set the initial state of an
object
• Constructors are called when an object is created using
the new operator
• A default constructor is a constructor with no parameters,
it initializes the instance variables to default values
• Restrictions on constructors
• constructor name must be the same as the class name
• constructor cannot return a value, not even void
• only an access modifier is allowed
25
Key Points
• Abstraction is the process of formulating general concepts by
extracting common properties of instances.
• A class is an abstraction of its instances.
• A Java Class denotes a category of objects.
• Class members refer to its fields and methods.
• Static members are variables and methods belonging to a class.
• Instance members are variables and methods belonging to
objects.
• Instantiating a class means creating objects of its own type.
• Class modifiers include: (no modifier), public, abstract,
final and strictfp.
• Member modifiers include: (no modifier), public, protected,
private, static, final, abstract, strictfp,
synchronized, native, transient and volatile.
26
Key Points (Continued)
• Encapsulation hides implementation details of a class.
• Encapsulating a class means declaring members with
minimum level of visibility.
• Setters are methods whose only function is to alter the
state of an object in a controlled manner.
• Getters are methods which only function is to return
information about the state of an object.
• Constructors are methods which set the initial state of an
object upon creation of the object.

More Related Content

What's hot (20)

Chap02
Chap02Chap02
Chap02
 
Inner class
Inner classInner class
Inner class
 
Metaprogramming ruby
Metaprogramming rubyMetaprogramming ruby
Metaprogramming ruby
 
Inner classes
Inner classesInner classes
Inner classes
 
Introducing classes
Introducing classesIntroducing classes
Introducing classes
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java(inheritance)
Java(inheritance)Java(inheritance)
Java(inheritance)
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
 
Uniform and Safe Metaclass Composition
Uniform and Safe Metaclass CompositionUniform and Safe Metaclass Composition
Uniform and Safe Metaclass Composition
 
Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Concept of Object-Oriented in C++
Concept of Object-Oriented in C++Concept of Object-Oriented in C++
Concept of Object-Oriented in C++
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
 
Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2
 
15reflection in c#
15reflection  in c#15reflection  in c#
15reflection in c#
 
Class1
Class1Class1
Class1
 

Similar to encapsulation and abstraction

class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview QestionsArun Vasanth
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptxAsifMulani17
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxDaveEstonilo
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAhmed Nobi
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questionsMehtaacademy
 
SystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfSystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfssusere9cd04
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078Aravind NC
 
04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdf04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdfmarkbrianBautista
 

Similar to encapsulation and abstraction (20)

class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Lecture09.ppt
Lecture09.pptLecture09.ppt
Lecture09.ppt
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
SystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfSystemVerilog_Classes.pdf
SystemVerilog_Classes.pdf
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
 
04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.pdf04_-_Inheritance_Polymorphism_and_Interfaces.pdf
04_-_Inheritance_Polymorphism_and_Interfaces.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
 

Recently uploaded

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 

Recently uploaded (20)

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

encapsulation and abstraction

  • 1. 08 Encapsulation and Abstraction
  • 2. 2 Contents • Defining Abstraction • Levels of Abstraction • Class as Abstraction • Defining a Java Class • Instantiating a Class • Class Members • Class Modifiers • Member Modifiers • Accessibility Scope • Defining Encapsulation • Principles of Encapsulation • Encapsulating a Class • Setters & Getters • Constructors
  • 3. 3 Objectives • Define abstraction • Identify levels of abstraction • Understand that a class is a form of abstraction • Define a Java class • Learn how to create objects by instantiating their class • Identify class members • Identify and define each modifier applicable to a class • Identify and define each modifier applicable to class members • Define access scope for class and its members • Know the purpose of constructors and how to create one for a class
  • 4. 4 Objectives (continued) • Define encapsulation • Describe the principles of encapsulation • Learn how to encapsulate a class • Learn how to use setters and getters
  • 5. 5 Defining Abstraction • Abstraction is the process of extracting common features from specific examples • Abstraction is a process of defining the essential concepts while ignoring the inessential details
  • 6. 6 Different Types of Abstraction • Data Abstraction Programming languages define constructs to simplify the way information is presented to the programmer. • Functional Abstraction Programming languages have constructs that ‘gift wrap’ very complex and low level instructions into instructions that are much more readable. • Object Abstraction OOP languages take the concept even further and abstract programming constructs as objects.
  • 7. 7 Anything that you can describe can be represented as an object, and that representation can be created, manipulated and destroyed to represent how you use the real object that it models. Everything is an Object
  • 8. 8 An object is a self-contained entity with attributes and behaviors Defining an Object information an object must know:  identity – uniqueness  attributes – structure  state – current condition behavior an object must do:  methods – what it can do  events – what it responds to
  • 9. 9 Class as Abstraction • A class is an abstraction of its instances. It defines all the attributes and methods that its instances must also have. Person name sex age tellSex() tellAge()
  • 10. 10 • A Class acts as the template from which an instance of an object is created. The class defines the properties of the object and the methods used to control the object's behavior. • A Class specifies the structure of data as well as the methods which manipulate that data. Such data and methods are contained in each instance of the class. • A Class is a model or template that can be instantiated to create objects with a common definition, and therefore common properties, operations and behavior. • A Class provides a template for defining the behavior of a particular type of object. Objects are referred to as “instances” of a class. Defining a Class
  • 11. 11 Defining a Java Class • A Java Class denotes a category of objects, and acts as a blueprint for creating such objects. • It defines its members referred to as fields and methods. • The fields (also known as variables or attributes) refer to the properties of the class. • The methods (also known as operations) refer to behaviors that the class exhibits. class Person { String name; char sex; int age; void tellSex() { if (sex=='M') System.out.println("I'm Male."); else if (sex=='F') System.out.println("I'm Female."); else System.out.println("I don't know!"); } void tellAge() { if (age<10) System.out.println("I'm just a kid."); else if (age<20) System.out.println("I'm a teenager."); else System.out.println("I'm a grown up."); } }
  • 12. 12 Class Members • A class member refers to one of the fields or methods of a class. • Static members are variables and methods belonging to a class where only a single copy of variables and methods are shared by each object. • Instance members are variables and methods belonging to objects where a copy of each variable and method is created for each object instantiated. class Person { static int maleCount; static int femaleCount; String name; char sex; int age; static void showSexDistribution() { if (maleCount>femaleCount) System.out.println("Majority are male."); else if (femaleCount>maleCount) System.out.println("Majority are female."); else System.out.println("Equal number of male and female."); } void tellSex() { if (sex=='M') System.out.println("I'm Male."); else if (sex=='F') System.out.println("I'm Female."); else System.out.println("I don't know!"); } void tellAge() { if (age<10) System.out.println("I'm just a kid."); else if (age<20) System.out.println("I'm a teenager."); else System.out.println("I'm a grown up."); } }
  • 13. 13 class Person { static int maleCount; static int femaleCount; String name; char sex; int age; static void showSexDistribution() { // method body here } void tellSex() { // method body here } void tellAge() { // method body here } } Instantiating a Class & Accessing its Members Access class variables by setting their values • Instantiating a class means creating objects of its own type. • The new operator is used to instantiate a class. class MainProgram { public static void main(String[] args) { // instantiating several objects Person p1 = new Person(); Person p2 = new Person(); Person p3 = new Person(); // accessing instance variables p1.name = "Vincent"; p1.sex = 'M'; p1.age = 8; p2.name = "Janice"; p2.sex = 'F'; p2.age = 19; p3.name = "Ricky"; p3.sex = 'M'; p3.age = 34; // accessing static variables Person.maleCount = 2; Person.femaleCount = 1; // accesssing instance methods p1.tellSex(); p1.tellAge(); p2.tellSex(); p2.tellAge(); p3.tellSex(); p3.tellAge(); // accessing static method Person.showSexDistribution(); } } Access class methods by invoking their names Create Person objects using the new operator. Sample Output: I'm Male. I'm just a kid. I'm Female. I'm a teenager. I'm Male. I'm a grown up. Majority are male.
  • 14. 14 Class Modifiers Modifier Description (no modifier) class is accessible within its package only public class is accessible by any class in any package abstract class cannot be instantiated (a class cannot be abstract and final at the same time) final class cannot be extended strictfp class implements strict floating-point arithmetic • Class modifiers change the way a class can be used. • Access modifiers describe how a class can be accessed. • Non-access modifiers describe how a class can be manipulated.
  • 15. 15 Access Modifiers Modifier Description (no modifier) member is accessible within its package only public member is accessible from any class of any package protected member is accessible in its class package and by its subclasses private member is accessible only from its class • Member modifiers change the way class members can be used • Access modifiers describe how a member can be accessed
  • 16. 16 Sample Package ClassClass Class Class Private features of the Sample class can only be accessed from within the class itself. Private features of the Sample class can only be accessed from within the class itself. private Classes that are in the package and all its subclasses may access protected features of the Sample class. Classes that are in the package and all its subclasses may access protected features of the Sample class. protected Only classes that are in the package may access default features of classes that are in the package Only classes that are in the package may access default features of classes that are in the package default All classes may access public features of the Sample class. All classes may access public features of the Sample class. public Class Class * Default is not a modifier; it is just the name of the access level if no access modifier is specified. Access Modifiers
  • 17. 17 Member Modifiers • Member modifiers change the way class members can be used • Non-access modifiers describe how a member can be manipulated Modifier Description static member belongs to a class final declares a constant variable or method abstract method is declared with no implementation (applied to methods, cannot be combined with other non-access modifiers ) strictfp method implements strict floating-point arithmetic (applied to methods) synchronized method is executed by only one thread at a time (applied only to methods) native method implementation is written in other language (applied only to methods) transient an instance variable is not saved when its object is persisted or serialized (applied only to variables) volatile variable is modified asynchronously by concurrently running threads (applied only to variables)
  • 18. 18 Accessibility Scope Scope Access static static code can access static members but not instance members non-static non-static code can access both static members and instance members package a class and its members can be accessed within the package they are declared class class members can be accessed within the class block local variables can be accessed only within a block • Accessibility scope defines the boundary of access to a class and its members
  • 19. 19 Defining Encapsulation • Encapsulation is the process of hiding an object’s implementation from another object, while presenting only the interfaces that should be visible.
  • 20. 20 Principles of Encapsulation “Don’t ask how I do it, but this is what I can do” - The encapsulated object “I don’t care how, just do your job, and I’ll do mine” - One encapsulated object to another
  • 21. 21 Encapsulating a Class • Members of a class must always be declared with the minimum level of visibility. • Provide setters and getters (also known as accessors/mutators) to allow controlled access to private data. • Provide other public methods (known as interfaces ) that other objects must adhere to in order to interact with the object.
  • 22. 22 Setters and Getters private char sex; public void setSex(char s) { // validate here sex = s; } public char getSex() { // format here return sex; } • Setters and Getters allow controlled access to class data • Setters are methods that (only) alter the state of an object • Use setters to validate data before changing the object state • Getters are methods that (only) return information about the state of an object • Use getters to format data before returning the object’s state
  • 23. 23 Encapsulation Example public static void main(String[] args) { // instantiate several objects Person p1 = new Person(); Person p2 = new Person(); Person p3 = new Person(); // access instance variables using setters p1.setName("Vincent"); p1.setSex('M'); p1.setAge(8); p2.setName("Janice"); p2.setSex('F'); p1.setAge(19); p3.setName("Ricky"); p3.setSex('M'); p3.setAge(34); // access static variables directly Person.maleCount=2; Person.femaleCount=1; // access instance methods p1.tellSex(); p1.tellAge(); p2.tellSex(); p2.tellAge(); p3.tellSex(); p3.tellAge(); // access static method Person.showSexDistribution(); } class Person { // set variables to private private static int maleCount; private static int femaleCount; private String name; private char sex; private int age; /* * setters & getters, set to public */ public int getAge() { return age;} public void setAge(int a) { age = a;} public String getName() { return name;} public void setName(String n) { name = n;} public char getSex() { return sex;} public void setSex(char s) { sex = s;} /* * set other methods as interfaces */ public static void showSexDistribution() { // implementation here } public void tellSex() { // implementation here } public void tellAge() { // implementation here } } I'm Male. I'm just a kid. I'm Female. I'm a teenager. I'm Male. I'm a grown up. Majority are male.
  • 24. 24 Constructors • Constructors are methods which set the initial state of an object • Constructors are called when an object is created using the new operator • A default constructor is a constructor with no parameters, it initializes the instance variables to default values • Restrictions on constructors • constructor name must be the same as the class name • constructor cannot return a value, not even void • only an access modifier is allowed
  • 25. 25 Key Points • Abstraction is the process of formulating general concepts by extracting common properties of instances. • A class is an abstraction of its instances. • A Java Class denotes a category of objects. • Class members refer to its fields and methods. • Static members are variables and methods belonging to a class. • Instance members are variables and methods belonging to objects. • Instantiating a class means creating objects of its own type. • Class modifiers include: (no modifier), public, abstract, final and strictfp. • Member modifiers include: (no modifier), public, protected, private, static, final, abstract, strictfp, synchronized, native, transient and volatile.
  • 26. 26 Key Points (Continued) • Encapsulation hides implementation details of a class. • Encapsulating a class means declaring members with minimum level of visibility. • Setters are methods whose only function is to alter the state of an object in a controlled manner. • Getters are methods which only function is to return information about the state of an object. • Constructors are methods which set the initial state of an object upon creation of the object.

Editor's Notes

  1. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 One of the primary goals of a high level programming language is the simplification of unfriendly, complex, low level computing instructions using a structure that is easier to use, understand organize, maintain and extend.
  2. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 Data Abstraction Everything to a computer is basically bits consisting of 1s and 0s, which is hardly intuitive for normal people. So language designers come up with primitive types like integers, characters etc… which hide the complexity of the bit patterns that are actually used. These can further be combined into something more meaningful. For example, the concept of a Birthdate can be the combination of 3 primitives to represent month, date, and year. This in turn can be combined with other higher level structures like, Name, Address etc.. to form an Employee Record . This is much easier to understand than 1s and 0s Functional Abstraction Would you rather write or read code written this way: 1 MOV 0x0064,A0 2 MOV 0x0096,Al 3 ADD A0,A1,A2 OR x = 150+100; Would you rather read this: int result = 1; for(int ctr = x; ctr &amp;gt;=2; ctr--){ result = result * ctr; } OR result = computeFactorial(int x) Object Abstraction Object abstraction builds on the previous two kinds of abstraction. Imagine a Car as an object. You want to drive a car. To drive a car, you all attend a driving school and study how to start a car, how to drive it, the proper driving etiquette etc… But driving school is different from automotive engineering school which teaches you how to build one. Now if your interest is only in driving, they only teach you how to drive a car. They leave out the very complex, probably interesting, but totally unnecessary mechanical engineering details. Also, when they teach you to drive a car, they don’t teach you to drive a particular kind of car. If you learn to drive using a sedan, that doesn’t necessarily mean, you cant drive a sports car or an SUV. They are all still cars with considerable differences but they are all generally driven the same way.
  3. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 So what is an object? In our previous discussion, we said that an object embodies its own unique behavior, and each one models some object in the real world (and is therefore something that exists in time and space). A car or a book are examples of such objects. You can describe a car, repair it, drive it, and/or even sell it. You can buy a book, read a book, and/or even provide a review of the book. But in the real world, tangible items are not the only kind of objects that are of interest to us during software development. A work assignment, for example, is not something you can touch but you can describe it, discuss it, assign it and/or complete it. Book borrowing is also not tangible but you can describe it, monitor it and/or report it. Basically, anything that you can describe can be represented as an object, and that representation can be created, manipulated and destroyed to represent how you use the real object that it models.
  4. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 Each object defines three basic types of information that it must know: 1. An object has to describe the features that will allow its users to distinguish it from other objects. It needs to have an identity. Even if two objects share the same features, each object has a unique identity. 2. An object must be able to describe itself. This type of information is stored in an object’s attributes and which form the object’s structure. 3. An object must be able to describe its current condition, called its state. Object state is sometimes represented by the values of each of its attributes. For example, a car can be brand new or worn out. Other times, the state is represented by the presence or absence of key relationships with other objects. For example, a book can be reserved or ordered. A reserved book has a relationship with the person who reserved it. An ordered book has a relationship with an order.
  5. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325
  6. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 Notes: We provided several definitions just to be comprehensive. In the real world, you often have many objects of the same kind. For example, your car is just one of the many cars in the world. However, your car has some attributes and methods that are common to other cars. This is because car manufacturers used a blueprint or template in building your car. It would be very inefficient to produce a new blueprint for every individual car that is manufactured. [1] In the object-oriented approach, this blueprint is called a class. A class is an abstract concept that describes how to build an accurate representation of a specific type of object. It contains variables that define the attributes of an object. It also contains operations that define the associated methods of an object. [2] Bibliography [1] http://java.sun.com/docs/books/tutorial/java/concepts/class.html [2] MDC Application Design School
  7. Notes: Each Person object created is separate and its state distinct from other objects created from the Person class. (The complete code for the Person class is found in the previous slide)
  8. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 Talking Points: The purpose and focus of this slide is to describe the degrees of access control or visibility for hiding information or implementation. Discuss each access level and differentiate them from one another. Access control is often referred to as implementation hiding.
  9. Only a few of these modifiers are commonly used in Java. Thus, not all of them will be discussed thoroughly in the succeeding topics.
  10. &amp;lt;number&amp;gt; © Accenture 2005 All Rights Reserved Course Code # Z16325 Notes: Encapsulation is the process of hiding details of an object or function. Implementation hiding is a powerful programming technique because it reduces complexity. Encapsulation means to design, produce, and describe software so that it can be easily used without knowing the details of how it works.
  11. Faculty Notes Encapsulation means to design, produce, and describe software so that it can be easily used without knowing the details of how it works. Programmers should only concern themselves with learning how to use an object, not how it works.
  12. Faculty Notes
  13. Talking Points: The purpose and focus of this slide is to show the use of setters and getters as part of protecting data in encapsulation. Setters and getters should be named by: Capitalizing the first letter of the variable (first becomes First), and Prefixing the name with get or set (setFirst) For boolean variables, you can replace get with is (for example, isRunning) This is more than just a convention—if and when you start using JavaBeans, it becomes a requirement
  14. Faculty Notes: Abstraction, implementation hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.