0% found this document useful (0 votes)
8 views

2-2 Encapsulation

Encapsulation involves storing data and methods that act on the data within the same class. There are three access levels in Java - private, protected, and public. Private members can only be accessed within the class, protected within the class and subclasses, and public by any class. Static variables are shared among all instances of a class and exist for the lifetime of the program. Access to private static variables must be through public static methods.

Uploaded by

De Shad Bostic
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)
8 views

2-2 Encapsulation

Encapsulation involves storing data and methods that act on the data within the same class. There are three access levels in Java - private, protected, and public. Private members can only be accessed within the class, protected within the class and subclasses, and public by any class. Static variables are shared among all instances of a class and exist for the lifetime of the program. Access to private static variables must be through public static methods.

Uploaded by

De Shad Bostic
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
You are on page 1/ 8

ENCAPSULATION

Encapsulation ......................................................................................................................................................... 1
Access Levels ........................................................................................................................................................................ 1
Private and Protected Classes ....................................................................................................................................... 2
Protocol of a Class............................................................................................................................................................... 3
Violation of the protected Access Level..................................................................................................................... 3
Static Scope ........................................................................................................................................................................... 4
Private Variables ............................................................................................................................................................ 4
Public Variables .............................................................................................................................................................. 5
Initialising Static Variables ........................................................................................................................................ 6
The Function main ....................................................................................................................................................... 7
Counting Class Instances ............................................................................................................................................ 7
Encapsulation

Encapsulation is the storing of data and those functions (methods) that act on it within the same
container. Note that in the case of object-oriented programming, the class is the container. On the
other hand, data hiding is the concealing of the data from the outside world (or other classes). For
the rest of the course, all references to encapsulation will include data hiding.

Encapsulation has the following benefits:

• Maintains the consistency of the data by controlling access to it.


• Hides the implementation details of the data.
• Avoids side effects when the data structure is changed.
• Encourages reuse via the black box method.

Access Levels

Java allows a user to determine the access levels of the fields and methods within a class. There are
three basic levels:

• private: Only the owner class has access to the fields and methods.
• protected: Both the owner class and its children (subclasses) have access to the fields and
methods.
• public: All classes have access to the fields and methods.

To clarify these three basic levels, consider the following code and figure 1.

public class BasicLevels


{ BasicLevels
// Fields
x
 private int x; y
Access by
members of
BasicLevels
 protected int y;
test

// Methods B
 public void test( int nx, int ny )
{ A Access by some
x = nx; Access by other class
y = ny; subclass
} // test Figure 1
} // BasicLevels

The field x is private, y is protected and test is public. As a result,

• x can only be accessed by BasicLevels.


• y can be accessed by BasicLevels and subclass A.
• test can be accessed by the subclass A and external class B.

Note that class A is a subclass of BasicLevels (see the Inheritance handout) and B is an external
class.

COMP2232 – Object-oriented Programming Concepts


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 1
Consider the following example from the Object Structure handout.

public class Agent


{
int age, height;

void set( int newAge, int newHeight )


{
age = newAge;
height = newHeight;
} // set
} // AnAgent

Both the fields and the method are public by default. However, it is good object-oriented design to
hide the details of the data from external classes. Access to the data is then provided by public
methods. This ensures that the class can maintain the integrity of the data. Consequently, the Agent
class is changed as follows.

public class Agent


{
 private int age, height;

 public void set( int newAge, int newHeight )


{
if( newAge > 0 )
age = newAge;

if ( newHeight > 0 )
height = newHeight;
} // set
} // Agent

As a result, the Agent class can maintain the integrity of its data via the set method. For example,
by ensuring that the values are positive, Agent is preserving its data integrity.

 If an access level is not specified then the default level is public.

Private and Protected Classes

You cannot create private or protected classes at the base level. This can only be done for inner
classes, which is not covered in this course.

COMP2232 – Object-oriented Programming Concepts


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 2
Protocol of a Class

The protocol, interface or


functionality of a class is
defined by its public methods
since it is these methods that
are accessible by external
classes. Generally, it is good
object-oriented design to hide
the class's data and only allow
access via the public methods
(the interface). Consider figure
2.

The class's private fields and


methods are within the
encapsulation boundary while
the public methods form an
interface that provides access to
them through the encapsulation
boundary.
Figure 2

Violation of the protected Access Level

As stated previously, protected methods and fields can be accessed by both the container class and
its subclasses. However, this access level fails when used in Java packages. A Java package allows
the grouping of a set of classes in a single container (see the Frameworks handout). For example,
the java.awt package contains the graphical user interface classes and the java.io package
contains the I/O classes.

Classes within the same package can access the protected members of any class in that package,
whether or not they are subclasses. Consider the following example.

package thePack;

public class Window


{
 protected int x, y;
} // Window

public class Button


{
} // Button

Since Window and Button are in the thePack package, Button can access the x and y values in
Window, even though it is not a subclass of Window. In other words, x and y are public to Button.

COMP2232 – Object-oriented Programming Concepts


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 3
Static Scope

A static variable is shared among all instances of the class in question. This is unlike normal
instance variables where each object has its own copy of the fields. This type of variable exists
throughout the lifetime of the program whether or not an instance of the class exists. As a result,
they are referred to as class variables. This means that when a Java program is loaded, all static
variables are created before the program is executed.

Private Variables

In the case of a private static variable, only the instances of the class can access it directly. External
classes on the other hand, must use public static methods for access. The method must be static so
that it exists with the static variable, even when no instances of the class have been created. In Java,
to declare a variable or method as static, use the static keyword. Consider the following example:

public class PrivateVar


{
private static int a;

public static int getA()


{
return a;
} // getA

} // PrivateVar

public class StaticDemo


{
public static void main( String args[] )
{
PrivateVar p = new PrivateVar();

 int x = p.getA(); //through an instance of PrivateVar


 int y = PrivateVar.getA(); //directly via the class PrivateVar
}
} // StaticDemo

This example demonstrates two techniques for accessing the private static variable a via a public
static method (see figure 3).
p
PrivateVar
new
int a
a = 2
getA()

main

x
y
Figure 3
COMP2232 – Object-oriented Programming Concepts
Faculty of Science & Technology, The University of the West Indies (Cave Hill) 4
Public Variables

In the case of a public static variable, it is accessible by all classes. This can either be through an
instance of the class or the class directly. Consider the following example:

public class PublicVar


{
public static int a;

//other methods

} // PublicVar

public class StaticDemo


{
public static void main( String args[] )
{
PublicVar p = new PublicVar();

 int x = p.a; // through an instance of PublicVar


 int y = PublicVar.a; // directly via the class PublicVar
}
} // StaticDemo

In this case, the public static variable a is accessible via instance p and directly through the class
PublicVar (see figure 4).

PublicVar new
a = 2
int a

//methods
main

x
Figure 4 y

COMP2232 – Object-oriented Programming Concepts


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 5
Initialising Static Variables

Static variables can only be initialised via a block labeled static. This enables the variable to be
initialised as soon as the class is loaded. Consider the following example:

public class InitStatic


{
private static int a;

 static
{
a = 1;
} // static

public static void main( String args[] )


{
...
}
} // InitStatic

The static variable a is initialised to 1 before the method main is called.

 Before a Java program is executed, the class loader loads the required classes.

This mechanism is preferred over constructors because a constructor is called each time an
instance of the class is created, resulting in the reinitializing of the static variables (see the
Constructors and Destructors handout). Consider the following example:

public class InitStatic


{
private static int a;

 InitStatic() //constructor
{
a = 1;
} // InitStatic

public static void setA( int new_a )


{
a = new_a;
} // setA

public static void main( String args[] )


{
InitStatic b = new InitStatic();
b.setA( 2 );
InitStatic c = new InitStatic();
}
} // InitStatic

As soon as object c is created, the value of variable a is reset back to 1. (Recall that all instances of
the class are sharing this variable.)

COMP2232 – Object-oriented Programming Concepts


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 6
The Function main

The function main is declared as both public and static. It is public so that the Java interpreter can
access it and it is static so that an instance of the containing class does not need to be created. Also,
by declaring it as static, a copy of main will be created before the program is executed. This enables
the function main to be the starting point of a Java program.

Counting Class Instances

The total number of instances of a class can be tracked using static variables. The following example
demonstrates this (see figure 5).

public class TrackInstance


{
private static int count;

// Statically initialise the count.


static
{
count = 0;
} // static

// Increment the count each time an instance is created.


TrackInstance()
{
count++;
} // TrackInstance

public static void main( String args[] )


{
TrackInstance b = new TrackInstance(); // count = 1
TrackInstance c = new TrackInstance(); // count = 2
}
} // TrackInstance

The variable count tracks the number of instances created. It is initialised to 0 when the class is
first loaded. Each time a new instance of the class is created, the constructor is called and count is
incremented by 1. Thus, after the creation of object instance c, the value of count is 2.

count = 2

b c

Figure 5

COMP2232 – Object-oriented Programming Concepts


Faculty of Science & Technology, The University of the West Indies (Cave Hill) 7

You might also like