0% found this document useful (0 votes)
20 views22 pages

05 Encapsulation

123

Uploaded by

Quân Hà Hoàng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views22 pages

05 Encapsulation

123

Uploaded by

Quân Hà Hoàng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 22

Packages

Package

 A package is a set of related classes

 Syntax to put a class into a package:

package <your.package.name>;
public class <ClassName> { …}

 Two rules:
 A package declaration must always come first in your .java file
 Naming convention: all lower case, with ‘.’ separating nested
package names, biggest package first.

 Example:
package cis1068.au10.graphics;
public class Point3D { … }
Using packaged classes

Two options for using classes in a package:


1) Use full class name:
<package.name>.<ClassName>
For example,
java.util.Scanner console
= new java.util.Scanner(System.in);

2) Import the package, use the “qualified” name:


At the top of the file, below any package declaration:
import <package.name>.<ClassName>; or
import <package.name>.*;
Then you can use <ClassName> anywhere, without the full package name.
For example,
import java.util.Scanner; … (and later) …
Scanner console = new Scanner(System.in);
Encapsulation

4
Encapsulation
 encapsulation: Hiding the implementation details of an
object from the clients of the object.

 Encapsulating objects provides abstraction, because we


can use them without knowing how they work.

? ??
? 5
Implementing encapsulation

 Fields can be declared private to indicate that no


code outside their own class can change them.

 Declaring a private field, general syntax:


private <type> <name>;

 Examples:
private int x;
private String name;

6
Access Specifiers

Access Keyword What code has access?


Public public All code has access
Only code in the same
Private private class has access
Only code in the same
class or a subclass
Protected protected has access
Code in the same
package has access
Package <nothing>* (this is the default)
*Note: Package-level access is specified by leaving out any keyword. It
is NOT specified using the package keyword, which is used for
something else!
7
Private fields

 Once fields are private, client code cannot directly


access them. The client receives an error such as:
PointMain3.java:8: x has private access in Point
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");

 How can the client program see what x is?

8
Accessors

 accessor: An instance method that provides


information about the state of an object.

 Example:
public int getX() {
return x;
}

 This gives clients "read-only" access to the object's


fields.

9
Mutators

 mutator: An instance method that modifies the


object’s internal state.

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

10
Mutable and Immutable objects

 Definition: An immutable object is an object whose


state cannot be modified after it is created.

 The String class and all the wrapper classes are


immutable in Java.
 As a result, we can’t use the wrapper classes to solve the swap
problem for primitive types.

 Point objects are mutable (ie, not immutable)


 setLocation and translate change their state
 We can use this fact to make the swap method work
Benefits of encapsulation

 Encapsulation helps provide a clean layer of abstraction


between an object and its clients.

 Encapsulation protects an object from unwanted access by


clients.
 Would you like any program to be able to modify the
BankAccount object with your account information?

 Encapsulation allows the class author to change the internal


representation later if necessary.
 Example: Changing the Point class to use polar
coordinates (a radius r and an angle θ from the origin)
12
The keyword this

13
Point class constructor
 What happens if the constructor has the following
header?
public Point3D(int x, int y, int z)

14
Variable shadowing

 shadowed variable: A field that is "covered up" by a local


variable or parameter with the same name.

 Normally, it is illegal to have two variables in the same


scope with the same name, but in this case (fields and
local variables) it is allowed. Why?

 Otherwise, to avoid shadowing, we would always have to


give the parameters different names:
public Point3D(int initialX, int initialY, int initialZ) {
x = initialX;
y = initialY;
z = initialZ;
}
15
Using the keyword this

 The this keyword is a reference to the implicit


parameter (the object on which an instance method
is being called).

 Usage of the this keyword, general syntax:


 To refer to a field:
this.<field name>

 To refer to a method:
this.<method name>(<parameters>);

16
It's like this and like that and like this and...

 The this keyword lets us use the same names and


avoid shadowing:

public Point3D(int x, int y, int z) {


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

 When this. is present, the field is used.


 When this. is not present, the parameter is used.

17
Wrapper
Classes
Wrapper classes

 Wrapper classes are object types that correspond to


each primitive type
Primitive Type Wrapper Class
int Integer
long Long
double Double
boolean Boolean
char Character
 Two important methods in Wrapper classes:
 parseInt(String s) (or parseDouble, parseLong …)
 intValue() (or doubleValue(), longValue(), …)

 Important fields: MAX_VALUE, MIN_VALUE


Converting between primitive and
Wrapper types

 You can wrap a int in an Integer by assignment:

int x = 17;
Integer wrapX = new Integer(x);
Integer wrapX2 = x; // shorthand

 To get an int value out of an Integer object:


Integer x = new Integer(17);
int unwrappedX = x.intValue();
int unwrappedX2 = x; // shorthand
Wrapper classes for swapping
ints
public static void main(String[] args) {
Integer a = 7;
Integer b = 35;
System.out.println(a + " " + b);

// swap a with b
swap(a, b);

System.out.println(a + " " + b);


}

public static void swap(Integer a, Integer b) {


Integer temp = a;
a = b;
b = temp;
}

 What’s wrong with this version?


Madness to the method
 The methods that appear to modify a string (substring,
toLowerCase, toUpperCase, etc.) actually create and
return a new string.

String s = "lil bow wow";


s.toUpperCase();
System.out.println(s); // output: lil bow wow

vs.

String s = "lil bow wow";


s = s.toUpperCase();
System.out.println(s); // output: LIL BOW WOW

22

You might also like