Download Effective Java: Classes and Interfaces - Encapsulation and Inheritance Best Practices and more Study notes Computer Science in PDF only on Docsity!
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science
4 – Effective Java: Classes and Interfaces
Items 14, 16, 20, 21, 22
CMPSCI 220 (291A)
Programming Methodology
Spring 2009
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 2
Effective Java: Classes and Interfaces
Ten items, of varying detail, complexity
All are good to follow, so …
You should read the whole chapter
We will present items of greatest relevance at
this moment in the course …
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 3
Effective Java – Item 14
You may be tempted to write a class like:
Class Point {
public double x;
public double y;
This breaks encapsulation. Why is that bad?
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 4
Problems with Degenerate Classes
Can’t change the representation without
changing all client code (no real “API”)
Can’t enforce invariants (“rules”)
Can’t take auxiliary action on update or use
So, shouldn’t do it!
… but maybe ok for a private class
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 5
What to do?
For each field of form Abc xyz :
Make it private (or at least protected )
Provide a getter:
public Abc getXyz() { return xyz; }
And a setter:
public void setXyz(Abc xyz)
{ this.xyz = xyz; }
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 6
How about final (immutable) fields?
Suppose you have public final Abc xyz = …;
Might be ok, since it avoid some of the
problems, but …
Still breaks encapsulation, makes changes
harder, etc.
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 7
Effective Java – Item 16
Implementation inheritance violates
encapsulation
Subclass depends on superclass details …
Makes it hard to change the superclass safely
Item 17 talks about how to do inheritance
right if it is the thing you’re going to do
But now, let’s take an example, see its
difficulties, and try to fix it
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 8
InstrumentedHashSet (IHS, HS)
public class IHS extends HashSet {
private cnt = 0; // constructors omitted
@Override public boolean add (E e)
{ cnt++; return super.add(e); }
@Override public boolean addAll (
Collection<? extends E> c) {
cnt += c.size();
return super.addAll(c);
public int getCnt () { return cnt; }
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 9
IHS details
public class IHS extends HashSet {
private cnt = 0; // constructors omitted
@Override public boolean add (E e)
{ cnt++; return super.add(e); }
This is an annotation. This particular annotation
documents that we know we are overriding
the superclass method.
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 10
IHS details
public class IHS extends HashSet …
This says IHS is generic; E is any class or
interface type (no primitives allowed)
It also says that it extends HashSet , a class
for hash sets whose elements match E.
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 11
IHS details
public boolean addAll (
Collection<? extends E> c) …
This says that c is some type Collection
where T extends E , but we don’t need the
name T here.
We’ll talk more about generics later, we expect.
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 12
Ok, so what’s wrong with it?
public class IHS extends HashSet {
@Override public boolean add (E e)
{ cnt++; return super.add(e); }
@Override public boolean addAll (
Collection<? extends E> c) {
cnt += c.size();
return super.addAll(c);
public int getCnt () { return cnt; }
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 19
Singleton Function Object
class StringLengthComparator {
private StringLengthComparator() { }
public static final StringLengthComparator
INSTANCE = new StringLengthComparator() ;
public int compare(String s1, String s2) {
return s1.length() -s2.length() ;
•Concrete strategy class is typically stateless
•Hence all instances are functionally equivalent
•Singleton saves unnecessary object creation costs
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 20
Passing the Function Object
What type for the function object parameter?
•StringLengthComparator no good -- allows only one strategy
•Define a Comparator interface
•Modify StringLengthComparator to implement it
// Strategy interface
public interface Comparator {
public int compare(T t1, T t2) ;
class StringLengthComparator implements Comparator {
// Same class body as before
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 21
Anonymous Strategy Classes?
Arrays.sort(stringArray, new Comparator() {
public int compare(String s1, String s2) {
return s1.length() -s2.length() ;
•Concrete strategy classes are often declared using
anonymous classes
•Each call creates a new instance
•If used often, better to store function object in a private
static final field (with descriptive name) and reuse it
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 22
Hosting Strategy Classes
Concrete strategy class need not be public to
export a concrete strategy
A host class can export a public static field
Or a static factory method (Item 1)
The strategy interface will be the type
Concrete strategy class can be a private nested
class of the host
Unlike anonymous class, allows implementing
additional interfaces
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 23
Hosting Strategy Classes
//Exporting a concrete strategy
class Host {
private static class StrLenCmp
implements Comparator, Serializable {
public int compare(String s1, String s2) {
return s1.length() -s2.length() ;
//Returned comparator is serializable
public static final Comparator
STRING_LENGTH_COMPARATOR = new StrLenCmp();
... //Rest of class omitted
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 24
Item 21: Summary
Implementing the Strategy pattern is a primary use
of function pointers
To implement the Strategy pattern in Java:
Declare an interface to represent the strategy
Create a class implementing this interface for each
concrete strategy
For single use strategies, can use an anonymous class
For repeated use strategies, a private static member class
exported as a public static final field whose type is the
strategy interface
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 25
Item 22: Favor static member
classes over nonstatic ones
This is about nested classes , classes defined inside other
classes.
Can be done four ways (!)
Static member class
Non-static member class
Anonymous class
Local class
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 26
Static member classes
Simplest case
Mostly an issue of scope and access:
The nested class can access static parts of the containing
class
It cannot access containing class instance fields: it is not
“inside” any instance of the containing class
It is just as efficient, etc., as any class – it just has a
longer, qualified, name
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 27
Static member class example
class TLC { // top-level class
static int sf; // static field
int nf; // instance field
static class SMC { // static member class
static int ssf = sf + TLC.sf;
int snf = sf + TLC.sf;
SMC smo = new SMC();
TLC.SMC obj = new TLC.SMC(); // etc.
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 28
Non-static member class example
class TLC { // top-level class
static int sf; // static field
int nf; // instance field
class NMC { // non-static member class
int nnf1 = sf + nf;
int nnf2 = TLC.sf + TLC.this.nf;
NMC getNewNMC () { return new NMC(); }
static NMC n = new NMC(); // error!
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 29
Non-static member classes
Each TLC instance can have many NMC
instances that refer to it
The NMC instances can all access the TLC
instances fields, etc.
Thus the NMC instances have pointers to
the TLC instances (called TLC.this)
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 30
Non-static member classes: picture
This is from Java Precisely, page 33:
TLC oo = new TLC();
TLC.NMC iol = oo.new NMC(), io2 = oo.new NMC();
TLC.SMC sio = new TLC.SMC();
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 37
Using hierarchy to do better
abstract class Figure {
abstract double area ();
Class Circle extends Figure {
final double radius;
Circle (double radius) {
this.radius = radius;
double area () {
return Math.PIradiusradius;
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 38
Using hierarchy to do better (2)
Class Rect extends Figure {
final double length;
final double width;
Rect (double length, double width) {
this.length = length;
this.width = width;
double area () {
return length*width;
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 39
Easy to add another:
class Square extends Rect {
public Square (double side) {
super(side, side);
But only if Figures are immutable!
(Why? ….)