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? ā¦.)