Lecture-6 Encapsulation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Lecture – 6

Encapsulation
Java Package
• A java package is a group of
similar types of classes,
interfaces and sub-packages.
– Built-in Packages ( java, lang,
awt, javax, swing, net, io, util)
– User defined Packages
• The package keyword is used to create a
package in java.

4-2
1.//save as Simple.java
2.package mypack;
3.public class Simple{
4. public static void main(String args[]){
Example
5. System.out.println("Welcome to package");

6. }
7.} How to run java package
program
How to compile java Java mypack.Simple
package
javac -d directory javafilename How to send the class file to another directory or
Example drive?
javac -d . Simple.java To Compile:
e:\sources> javac -d c:\classes Simple.java
• The -d switch specifies the To Run:
destination where to put the Set the class path and then run
generated class file. e:\sources> set classpath=c:\classes;
• You can use any directory name e:\sources> java mypack.Simple
like d:/abc (windows). OR
• If you want to keep the package e:\sources> java -classpath c:\classes mypack.Simple
within the same directory, you can
4-3
use . (dot).
Information Hiding
• Information hiding means that you separate the description of
how to use a class from the implementation details,
– Such as how the class methods are defined
– Another term for information hiding is abstraction
– To drive a car, do you need to know how the engine works? Why?
• println method
– need to know what the method does
– but not how println does it

• Provide a more abstract view and hide the details


Defining Encapsulation
• Encapsulation means that the data and the methods are
combined into a single unit know as a class
• The details of the implementation are hidden.
• Information hiding and Encapsulation are two sides of the same
coin.

5
Benefits of Encapsulation
• Data Hiding: Encapsulation allows you to hide the internal state of an
object from the outside world.
– Data within an object can only be accessed and modified through well-
defined methods (getters and setters)
– Prevent unauthorized or unintended changes to an object's state.
• Abstraction: Create abstractions by exposing only the necessary details
of an object and hiding its implementation details.
– Users of the class do not need to know how the data is stored or how methods
are implemented
• Access Control: Encapsulation allows you to control access to data members by
defining them as private, protected, or public
4-6
Controlling access to class members
• Access Modifier
– Determines access rights for the class and its members
– Defines where the class and its members can be used
Why use these
• It is important in many applications to hide data from the
programmer
– E.g., a password program must be able to read in a password and
compare it to the current one or allow it to be changed
– But the password should never be accessed directly!

public class Password { Password ProtectMe;


public String my_password; …
… ProtectMe.my_password = “backdoor”; // this is
} bad
Access Modifiers
• Member modifiers change the way class members can be used
• Access modifiers describe how a member can be accessed
Modifier Description
(no modifier) The access level is only within the package. It cannot be accessed from outside the
/ default package. If you do not specify any access level, it will be the default.
The access level is everywhere. It can be accessed from within the class, outside the
public class, within the package and outside the package.

The access level is within the package and outside the package through child class. If you
Protected
do not make the child class, it cannot be accessed from outside the package.
Private The access level is only within the class. It cannot be accessed from outside the class.

9
Access Modifiers

outside package
Access Modifier Within class Within Package outside package
by subclass only

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

4-10
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 interact with the object.

11
Accessors and Mutators
• Accessor methods: Public methods that allow attributes
(instance variables) to be read
– Get methods are also commonly called accessor methods
– Much better than making instance variables public
• Mutator methods: Public methods that allow attributes
(instance variables) to be modified
– Set methods are also commonly called mutator methods,
because they typically change an object’s state
Setters and Getters
• 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

13
Example
public class Person { public class Main {
private String name; // private = restricted access public static void main(String[] args) {
Person myObj = new Person();
// Getter myObj.name = "John"; // error
public String getName() { System.out.println(myObj.name); // error
return name; }
} }

// Setter
public void setName(String newName) { Correct Solution
name = newName; public class Main {
} public static void main(String[] args) {
} Person myObj = new Person();
myObj.setName("John"); // Set the value of the name
variable to "John"
System.out.println(myObj.getName());
}
}
4-14
Using Reference of an Object Directly in a
Setter
Inside the 'Array' class we have a private array which is
an 'element'.
We have written a setElement() setter function in which values of
one array are copied into the array declared inside the class.
So the 'element' array values are set which is the same as
the 'Arr' array which is declared inside the main method.

4-15
public class Main {
class Array { public static void main(String[] args) {
private int[] element; Array a1 = new Array();

//setter method to copy the value of a in element array int Arr[] = {5, 8, 11, 22, 33};
void setElement(int[] a) {
element = a; // calling the setter function
} a1.setElement(Arr);

//to print the value of the element array // calling the display function
void display() { a1.display();
//using .length function
//to find length of an array // new value is set at the 0th index
int len = element.length; Arr[0] = 2;
System.out.println();
for(int i = 0; i < len; i++) {
System.out.print(element[i] + " "); // calling the display function one more time
} a1.display();
} }
} }
5 8 11 22 78
2 8 11 22 78 4-16
class Array {
private int[] element;
public class Main {
void setElement(int[] a) {
public static void main(String[] args) {
int len2 = a.length;
Array a1 = new Array();
// dynamically allocating the memory to element[]
// according to the a[] array length
int Arr[] = {5, 8, 11, 22, 78};
element = new int[len2];
for(int i = 0; i < len2; i++) {
// calling the setter function
// copying the value one by one
a1.setElement(Arr);
// into the element array
element[i] = a[i];
// calling the display function
}
a1.display();
}
// to print the value of the element array
// new value is set at the 0th index
void display() { //using .length function
Arr[0] = 2;
//to find length of an array
System.out.println();
int len = (this.element).length;
// calling the display function one
for(int i = 0; i < len; i++) {
more time
System.out.print(this.element[i] + " ");
a1.display();
}
}
} 5 8 11 22 78 }
} 5 8 11 22 78 4-17

You might also like