08 encapsulation and abstraction. 2 contents defining abstraction levels of abstraction class as...

26
08 Encapsulation and Abstraction

Upload: blaze-gibson

Post on 17-Jan-2016

235 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

08 Encapsulation and Abstraction

Page 2: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

2

ContentsContents

• 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

Page 3: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

3

ObjectivesObjectives

• 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

Page 4: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

4

Objectives (continued)Objectives (continued)

• Define encapsulation• Describe the principles of encapsulation• Learn how to encapsulate a class• Learn how to use setters and getters

Page 5: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

5

Defining AbstractionDefining 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

Page 6: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

6

Different Types of AbstractionDifferent 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.

Page 7: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

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

Everything is an Object

Page 8: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

8

An object is a self-contained entity

with attributes and behaviors

Defining an ObjectDefining 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

Page 9: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

9

Class as AbstractionClass as Abstraction

• A class is an abstraction of its instances. It defines all the attributes and methods that its instances must also have.

Person

namesexage

tellSex()tellAge()

Page 10: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

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 ClassDefining a Class

Page 11: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

11

Defining a Java ClassDefining 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.");}

}

Page 12: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

12

Class MembersClass 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.");}

}

Page 13: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

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 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.

Page 14: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

14

Class ModifiersClass 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.

Page 15: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

15

Access ModifiersAccess 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

Page 16: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

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 ModifiersAccess Modifiers

Page 17: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

17

Member ModifiersMember 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)

Page 18: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

18

Accessibility ScopeAccessibility 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

Page 19: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

19

Defining EncapsulationDefining Encapsulation

• Encapsulation is the process of hiding an object’s implementation from another object, while presenting only the interfaces that should be visible.

Page 20: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

20

Principles of Encapsulation 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

Page 21: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

21

Encapsulating a ClassEncapsulating 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.

Page 22: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

22

Setters and GettersSetters and Getters

private char sex;

public void setSex(char s) {// validate heresex = s;

}public char getSex() {

// format herereturn 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

Page 23: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

23

Encapsulation Example Encapsulation Example public static void main(String[] args) {

// instantiate several objectsPerson p1 = new Person();Person p2 = new Person();Person p3 = new Person();

// access instance variables using settersp1.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 directlyPerson.maleCount=2;Person.femaleCount=1;

// access instance methodsp1.tellSex(); p1.tellAge();p2.tellSex(); p2.tellAge();p3.tellSex(); p3.tellAge();

// access static methodPerson.showSexDistribution();

}

class Person {// set variables to privateprivate 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.

Page 24: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

24

ConstructorsConstructors

• 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

Page 25: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

25

Key PointsKey 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.

Page 26: 08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class

26

Key Points (Continued)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.