0% found this document useful (0 votes)
10 views35 pages

Understanding Encapsulation in OOP

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on encapsulation, which is the practice of hiding implementation details and protecting an object's data integrity. It outlines guidelines for defining well-encapsulated classes, the use of access modifiers in Java, and the importance of accessor and mutator methods. Additionally, it discusses the benefits of encapsulation, variable naming, constructors, and the use of UML class diagrams in programming.

Uploaded by

furkanacikdeniz
Copyright
© All Rights Reserved
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
0% found this document useful (0 votes)
10 views35 pages

Understanding Encapsulation in OOP

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on encapsulation, which is the practice of hiding implementation details and protecting an object's data integrity. It outlines guidelines for defining well-encapsulated classes, the use of access modifiers in Java, and the importance of accessor and mutator methods. Additionally, it discusses the benefits of encapsulation, variable naming, constructors, and the use of UML class diagrams in programming.

Uploaded by

furkanacikdeniz
Copyright
© All Rights Reserved
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

OBJECT ORIENTED PROGRAMMING

Dr. Seyit KAYA


ENCAPSULATION
ABSTRACTION
Don't need
to know
this

Can focus
on this!!

I am a user
ENCAPSULATION
▪ encapsulation: Hiding implementation details of an
object from its clients.

▪ Encapsulation provides abstraction.


▪ separates external view (behavior) from internal view (state)

▪ Encapsulation protects the integrity of an object's data.


ENCAPSULATION

▪ This is the process of hiding all of the details of a class


definition to make using the class easier.
▪ When done correctly, a class can be divided into two parts,
the user interface and the implementation.
▪ The implementation consists of all the private instance
variables of a class and the definitions of all the methods,
both public and private.
ENCAPSULATION (CONT’D)

▪ The user interface consists of all the headings for the public
methods and defined constants of the class, along with
comments that tell a programmer how to use these public
methods and public defined constants.
▪ When a class is defined in a way that conceptually separates
the user interface and the implementation we say that the
class is well encapsulated.
GUIDELINES FOR DEFINING A WELL-ENCAPSULATED
CLASS

1. Place a comment before the class definition that


describes how the programmer should think about the
class data and methods.
2. Declare all instance variables in the class to be
private.
3. Provide public accessor and mutator methods to read
and change data in an object of the class and any other
methods a programmer may need to manipulate data in
the class, e.g., input and output methods.
GUIDELINES FOR DEFINING A WELL-ENCAPSULATED
CLASS (CONT’D)

4. Fully specify how to use each public method with a


comment placed before the method heading.
5. Make any helping methods (methods to be used only by
other methods of the class) private.
6. Place all user interface comments (those that describe
how to use the class or method of the class) before the
class definition and before public method definitions.
A general rule is to use /* */ comments for user interface
comments and // comments for implementation
comments.
EXAMPLE
▪ Create an Account Class With the following attributes;

▪ private long acc_no;

▪ private String name,email;

▪ private float amount;


AUTOMATIC DOCUMENTATION WITH JAVADOC

▪ javadoc is a tool that automatically generates user


interface documentation for your classes.
▪ javadoc extracts comments and other information from
your classes to provide the information necessary for
someone to use your program, but the usefulness of the
documentation depends, in part, on the usefulness of the
comments you place in your code.
ACCESS MODIFIERS IN JAVA
▪ There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do
not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the
package and outside the package.
ACCESS CONTROL IN JAVA (2)
Class 1
Package
public
members
protected members Class 3 ©
Am
ma
nn
&
default Off
utt

private members

inheritance
Intr
od
Class 2 ucti
on
to
Sof
twa
re
Tes

12 Class 5 Class 4 ting


,
edit
ion
2
1-PRIVATE FIELDS
▪ A field can be declared private.
▪ No code outside the class can access or change it.

private type name;


▪ Examples:
private int id;
private String name;

▪ Client code sees an error when accessing private fields:

[Link]: x has private access in Point


[Link]("p1 is (" + p1.x + ", " + p1.y + ")");
^
ACCESSING PRIVATE STATE

▪ We can provide methods to get and/or set a field's value:

// A "read-only" access to the x field ("accessor")


public int getX() {
return x;
}

// Allows clients to change the x field ("mutator")


public void setX(int newX) {
x = newX;
}

▪ Client code will look more like this:

[Link]("p1: (" + [Link]() + ", " + [Link]() + ")");

[Link](14);
POINT CLASS
// A Point object represents an (x, y) location.
public class Point {
private int x;
private int y;

public Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

public double distanceFromOrigin() {


return [Link](x * x + y * y);
}

public int getX() {


return x;
}

public int getY() {


return y;
}

public void setLocation(int newX, int newY) {


x = newX;
y = newY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}
}
CLIENT CODE, VERSION 4
public class PointMain4 {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point(5, 2);
Point p2 = new Point(4, 3);

// print each point


[Link]("p1: (" + [Link]() + ", " + [Link]() + ")");
[Link]("p2: (" + [Link]() + ", " + [Link]() + ")");

// move p2 and then print it again


[Link](2, 4);
[Link]("p2: (" + [Link]() + ", " + [Link]() + ")");
}
}

OUTPUT:
p1 is (5, 2)
p2 is (4, 3)
p2 is (6, 7)
BENEFITS OF ENCAPSULATION
▪ Provides abstraction between an object and its clients.

▪ Protects an object from unwanted access by clients.


▪ A bank app forbids a client to change an Account's balance.

▪ Allows you to change the class implementation.


▪ Point could be rewritten to use polar coordinates
(radius r, angle θ), but with the same methods.

▪ Allows you to constrain objects' state (invariants).


▪ Example: Only allow Points with non-negative coordinates.
THIS KEYWORD

18
THIS
▪ this : A reference to the implicit parameter.
▪ implicit parameter: object on which a method is called

▪ Syntax for using this:


▪ To refer to a field:
[Link]

▪ To call a method:
[Link](parameters);

▪ To call a constructor from another constructor:


this(parameters);
VARIABLE NAMES AND SCOPE
▪ Usually it is illegal to have two variables in the same scope with the same name.
public class Point {
int x;
int y;
...

public void setLocation(int newX, int newY) {


x = newX;
y = newY;
}
}

▪ The parameters to setLocation are named newX and newY to be distinct from the object's
fields x and y.
VARIABLE SHADOWING
▪ An instance method parameter can have the same name as one of the
object's fields:

// this is legal
public void setLocation(int x, int y) {
...
}

▪ Fields x and y are shadowed by parameters with same names.


▪ Any setLocation code that refers to x or y will use the parameter, not the
field.
AVOIDING SHADOWING W/ THIS
public class Point {
private int x;
private int y;

...

public void setLocation(int x, int y) {


this.x = x;
this.y = y;
}
}

▪ Inside the setLocation method,


▪ When this.x is seen, the field x is used.
▪ When x is seen, the parameter x is used.
MULTIPLE CONSTRUCTORS

▪ It is legal to have more than one constructor in a class.

▪ The constructors must accept different parameters.

public class Point {


private int x;
private int y;

public Point() {
x = 0;
y = 0;
}

public Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

...
}
CONSTRUCTORS AND THIS
▪ One constructor can call another using this:
public class Point {
private int x;
private int y;

public Point() {
this(0, 0); // calls the (x, y) constructor
}

public Point(int x, int y) {


this.x = x;
this.y = y;
}

...
}
THE PUBLIC AND PRIVATE MODIFIERS
▪ It is considered good programming practice to make all instance
variables private.
▪ Whenever you place the modifier private before an instance
variable, that instance variable’s name is not accessible outside of the
class definition.
▪ Only methods within the class can access instance variables that are
declared to be private.
THE PUBLIC AND PRIVATE MODIFIERS (CONT’D)
▪ This does not mean that you cannot change the values of private
instance variables from outside the class where they are declared.
▪ It only means that you must invoke a method from within the class to
set or change values of instance variables.
▪ This means, of course, that the class must have methods to accomplish
this.
ACCESSOR(GETTER) AND
MUTATOR(SETTER) METHODS
▪ All instance variables should be private, and accessor and mutator
methods should be provided for accessing and setting or changing
values of instance variables from outside their class.
▪ A public method that reads and returns data from one or more private
instance variables is called an accessor method.
ACCESSOR AND MUTATOR METHODS (CONT’D)
▪ Names of accessor methods typically begin with get.
▪ A public method that changes the data stored in one or more private
instance variables is called a mutator method.
▪ Names of mutator methods typically begin with set.
EXAMPLE OF A MUTATOR METHOD
public void set(String newName, int newPopulation, double newGrowthRate){

name = newName;

if (newPopulation >= 0)

population = newPopulation;

else {

[Link]( “ERROR: using a negative population.”);

[Link](0);

growthRate = newGrowthRate;

}
EXAMPLE OF ACCESSOR METHODS

public String getName();


{
return name;
}
public String getPopulation();
{
return population;
}
public String getGrowthRate();
{
return growthRate;
}
UML CLASS DIAGRAMS
▪ Class diagrams are normally created before the class is defined.
▪ They provide a guide to the programmer in implementing the code
necessary to solve the problem at hand.
▪ A minus sign before an instance variable or method indicated that it is
private. A plus sign means that it is public.
UML CLASS DIAGRAM EXAMPLE
Purchase
- name: String
- groupCount: int
- groupPrice: double
- numberBought: int

+ setName(String newName): void


+ setPrice(int count, double costForCount): void
+ setNumberBought(int number): void
+ readInput( ): void
+ writeOutput( ): void
+ getName( ): String
+ getTotalCost( ): double
+ getUnitCost( ): double
+ getNumberBought( ): int
EXERCISE

Create a class for the UML diagram.


Then create a test app to test the class.
Get the values by console.
NESTED/INNER CLASSES

Java lets you define a class as a member of another class. Such a class is
called a nested class and is illustrated here:
class EnclosingClass{
...
class ANestedClass {
...
}
}

Definition: An inner class is a nested class whose instance exists


within an instance of its enclosing class and has direct access to the
instance members of its enclosing instance.

You might also like