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

Lecture 2

The document discusses encapsulation in programming, emphasizing the importance of hiding implementation details and protecting object data integrity. It covers private fields, accessors, mutators, and the use of the 'this' keyword, along with the benefits of encapsulation such as abstraction and state constraints. Additionally, it introduces static methods and fields, modular programming with classes, and the organization of classes into packages for better code management and visibility control.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 2

The document discusses encapsulation in programming, emphasizing the importance of hiding implementation details and protecting object data integrity. It covers private fields, accessors, mutators, and the use of the 'this' keyword, along with the benefits of encapsulation such as abstraction and state constraints. Additionally, it introduces static methods and fields, modular programming with classes, and the organization of classes into packages for better code management and visibility control.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

FCDS

Programming II

Lecture 2: Encapsulation
Encapsulation
• encapsulation: Hiding implementation details from clients.
– Encapsulation forces abstraction.
• separates external view (behavior) from internal view (state)
• protects the integrity of an object's data
Private fields
A field that cannot be accessed from outside the class

private type name;

– Examples:
private int id;
private String name;

• Client code won't compile if it accesses private fields:


PointMain.java:11: x has private access in Point
System.out.println(p1.x);
^
Accessing private state
// 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:


System.out.println(p1.getX());
p1.setX(14);
Point class, version 3
// A Point object represents an (x, y) location.
public class Point {
private int x;
Access private int y;
(Visibility) public Point(int initialX, int initialY) {
x = initialX;
Modifiers y = initialY;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}
public void translate(int dx, int dy) {
setLocation(x + dx, y + dy);
}
}
Benefits of encapsulation
• Abstraction between object and clients

• Protects object from unwanted access


– Example: Can't fraudulently increase an Account's balance.

• Can change the class implementation later


– Example: Point could be rewritten in polar
coordinates (r, θ) with the same methods.

• Can constrain objects' state


– Example: Only allow Accounts with non-negative balance.
– Example: Only allow Dates with a month from 1-12.
The this keyword
• this : Refers to the implicit parameter inside your
class.
(a variable that stores the object on which a method is called)

– Refer to a field: this.field

– Call a method: this.method(parameters);

– One constructor this(parameters);


can call another:
Variable shadowing
• shadowing: 2 variables with same name in same scope.
– Normally illegal, except when one variable is a field.

public class Point {


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

– In most of the class, x and y refer to the fields.


– In setLocation, x and y refer to the method's parameters.
Fixing shadowing
public class Point {
private int x;
private int y;
...
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
}

• Inside setLocation,
– To refer to the data field x, say this.x
– To refer to the parameter x, say x
Calling another constructor
public class Point {
private int x;
private int y;

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

public Point(int x, int y) {


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

...
}

• Avoids redundancy between constructors


• Only a constructor (not a method) can call another constructor
Static methods/fields
Multi-class systems
• Most large software systems consist of many classes.
– One main class runs and calls methods of the others.

• Advantages:
– code reuse
– splits up the program logic into manageable chunks
Main Class #1
main
method1
method2

Class #2 Class #3
method3 method4
method5 method6
Example (Static methods)
// This program sees whether some interesting numbers are prime.
public class Primes1 {
public static void main(String[] args) {
int[] nums = {1234517, 859501, 53, 142};
for (int i = 0; i < nums.length; i++) {
if (isPrime(nums[i])) {
System.out.println(nums[i] + " is prime");
}
}
}
// Returns the number of factors of the given integer.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of the number
}
}
return count;
}
// Returns true if the given number is prime.
public static boolean isPrime(int number) {
return countFactors(number) == 2;
}
}
Classes as modules
• module: A reusable piece of software, stored as a class.
– Example module classes: Math, Arrays, System
// This class is a module that contains useful methods
// related to factors and prime numbers.
public class Factors {
// Returns the number of factors of the given integer.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of the number
}
}
return count;
}
// Returns true if the given number is prime.
public static boolean isPrime(int number) {
return countFactors(number) == 2;
}
}
More about modules
• A module is a partial program, not a complete program.
– It does not have a main. You don't run it directly.
– Modules are meant to be utilized by other client classes.

• Syntax:
class.method(parameters);

• Example:
int factorsOf24 = Factors.countFactors(24);
Using a module
// This program sees whether some interesting numbers are prime.
public class Primes {
public static void main(String[] args) {
int[] nums = {1234517, 859501, 53, 142};
for (int i = 0; i < nums.length; i++) {
if (Factors.isPrime(nums[i])) {
System.out.println(nums[i] + " is prime");
}
}
}
}
// This program prints all prime numbers up to a given maximum.
public class Primes2 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Max number? ");
int max = console.nextInt();
for (int i = 2; i <= max; i++) {
if (Factors.isPrime(i)) {
System.out.print(i + " ");
} }
System.out.println();
}
}
Modules in Java libraries
// Java's built in Math class is a module
public class Math {
public static final double PI =
3.14159265358979323846;

...

public static int abs(int a) {


if (a >= 0) {
return a;
} else {
return -a;
}
}

public static double toDegrees(double radians) {


return radians * 180 / PI;
}
}
Static fields
private static type name;
or,
private static type name = value;

– Example:
private static int theAnswer = 42;

• static field: Stored in the class instead of each object.


– A "shared" global field that all objects can access and modify.
– Like a class constant, except that its value can be changed.
Accessing static fields
• From inside the class where the field was declared:
fieldName // get the value
fieldName = value; // set the value

• From another class (if the field is public):


ClassName.fieldName // get the value
ClassName.fieldName = value; // set the value
BankAccount
public class BankAccount {
// static count of how many accounts are created
// (only one count shared for the whole class)
private static int objectCount = 0;

// fields (replicated for each object)


private String name;
private int id;

public BankAccount() {
objectCount++; // advance the id, and
id = objectCount; // give number to account
}
...
public int getID() { // return this account's id
return id;
}
}
Static methods
// the same syntax you've already used
for methods
public static type name(parameters) {
statements;
}

• static method: Stored in a class, not in an object.


– Shared by all objects of the class, not replicated.
– Does not have any implicit parameter, this;
therefore, cannot access any particular object's fields.
– Statics methods can access only static fields.
BankAccount solution
public class BankAccount {
// static count of how many accounts are created
// (only one count shared for the whole class)
private static int objectCount = 0;
// clients can call this to find out # accounts created
public static int getNumAccounts() {
return objectCount;
}
// fields (replicated for each object)
private String name;
private int id;
public BankAccount() {
objectCount++; // advance the id, and
id = objectCount; // give number to account
}
...
public int getID() { // return this account's id
return id;
}
}
Static methods vs Instance methods
• Instance methods:
– Belongs to an object of the class
– Requires an object of its class to be created before it is called.
Ex: p.setLocation(3, 5) (where p is an object of class Point).
• Static methods:
– Can be called without creating an object of the class
– Can be called by the class name or an object of the class.
Ex: BankAccount.getNumAccounts() (using class name)
Obj.getNumAccounts() (using an object, where Obj is an
object of the
class BankAccount)
Packages
• Java allows programmers to organize their classes in
folder-like structure called package hierarchy
• Packages in Java is a mechanism for:
– Managing and partitioning the class name space: allowing
programmer to use same names for different classes without
conflicts.
– Visibility control: allowing programmer to specify who access
their classes
– It also imposes modularity and eases maintainability of code.

24
Defining a Class as part of a Package
• Include “package” keyword as the first statement in the class
followed by the package name
• Example:
package myPackage ;
This specifies that the class is part of package myPackage (the class must be
stored in a folder called myPackage)
• If you omit the package definition from the class the class is put in
the default package
• You can create a hierarchy of packages
• Example:
package
java2.lec3.myPakage ;
25
Accessing Classes in a Package
• To bring a class in certain package to visibility in your class you need to use the
“import” keyword
• Example:
import java2.lec3.myPakage.Stack ;
• You could also import the entire package in one step using *
• Example:
import java2.lec3.myPakage.* ;
(note: import this might negatively affect program compilation time)

• You may also access a class in certain package directly by specifying its package
as a prefix
• Example:
java2.lec3.myPakage.Stack s1 ;

26
Access Control
Access to member of a class can be defined as follows:
Specifier public Default (No private
Access from specifier)

Same Class √ √ √
Same Package √ √ X

Different Package √ X X

27

You might also like