HttpRequest, Player, Shape, Font
currentFont.size = 16
currentFont.size = PointsToPixels (12);
currentFont.sizeInPixels = PointsToPixels (12);
currentFont.attribute |= 0x02;
currentFont.attribute |= FONT_ATTRIBUTE_BOLD;
currentFont.bold = true
currentFont.setSizeInPixels (sizeInPixels);
currentFont.setSizeInPoints (sizeInPoints);
currentFont.setWeight (FontWeight.BOLD);
currentFont.setTypeFace (typeFaceName);
currentFont.setStyle (FontStyle.ITALIC);
ErrorMessages představuje seznam chybových
hlášení, reprezentovaných třídou Message.
public class Program {
...
public void initializeCommandStack();
public void pushCommand(Command command);
public Command popCommand();
public void shutdownCommandStack();
...
public void initializeReportFormatting();
public void formatReport(Report report);
public void printReport(Report report);
...
}
public class Program {
...
public void initializeProgram();
public void shutdownProgram();
...
}
public class Team extends ArrayList<Athlete> {
...
// public methods
public void setName(TeamName teamName);
public void setCountry(CountryCode countryCode);
...
// public methods inherited from ArrayList
public void add(Athlete athlete);
public void clear();
public boolean isEmpty();
public void ensureCapacity(int minCapacity);
...
}
public class Team {
...
// public methods
public void setName(TeamName teamName);
public void setCountry(CountryCode countryCode);
...
public void addMember(Athlete athlete);
public void removeMember(Athlete athlete);
...
private List<Athlete> members;
}
public class Employee {
...
public Employee(...);
public FullName getFullName();
public Address getAddress();
public PhoneNumber getWorkPhone();
public PhoneNumber getHomePhone();
public TaxId getTaxId();
public JobClassification getJobClassification();
...
}
public class Employee {
...
public Employee(...);
public FullName getFullName();
public Address getAddress();
public PhoneNumber getWorkPhone();
public PhoneNumber getHomePhone();
public TaxId getTaxId();
public JobClassification getJobClassification();
...
public boolean isJobClassificationValid(JobClassification job);
public boolean isZipCodeValid(Address address);
public boolean isPhoneNumberValid(PhoneNumber phoneNumber);
...
public SqlQuery getQueryToCreateNewEmployee();
public SqlQuery getQueryToModifyEmployee();
...
}
class Car {
private Engine engine;
private Wheel[] wheels;
}
Employee dědí z třídy PersonSupervisor dědí z třídy ... ?Employee a Supervisor mohou být role
public class CountingHashSet<E> extends HashSet<E> {
private int addCount = 0;
public CountingHashSet() {}
public CountingHashSet(int initCap, float loadFactor) {
super(initCap, loadFactor);
}
@Override
public boolean add(E e) {
addCount++;
return super.add (e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
}
CountingHashSet<String> s = new CountingHashSet<String>();
s.addAll(Arrays.asList("Snap", "Crackle", "Pop"));
System.out.println("Element additions: " + s.getAddCount());
6
super.addAll() nejspíš volá add()
public class ForwardingSet<E> implements Set<E> {
private final Set<E> target;
public ForwardingSet(Set<E> target) { this.target = target; }
public void clear() { target.clear(); }
public boolean contains(Object obj) { return target.contains(obj); }
...
public boolean add(E element) { return target.add(element); }
public boolean addAll(Collection<? extends E> elements) {
return target.addAll(elements);
}
...
@Override public boolean equals(Object obj) { return target.equals(obj); }
@Override public int hashCode() { return target.hashCode(); }
@Override public String toString() { return target.toString(); }
}
public class CountingSet<E> extends ForwardingSet<E> {
private int addCount = 0;
public CountingSet() {}
public CountingSet(Set<E> target) { super(target); }
@Override public boolean add(E element) {
addCount++;
return super.add(element);
}
@Override public boolean addAll(Collection<? extends E> elements) {
addCount += elements.size();
return super.addAll(elements);
}
public int getAddCount() {
return addCount;
}
}
Chceme definovat třídy Real a Complex,
představující reálná a komplexní čísla – jak bychom použili dědičnost?
Complex dědí od Real
Real dědí od Complex
Real bude jednoduše mít nulovou komplexní složkuJak z toho ven?
Nepoužijeme dědičnost, ale kompozici!
Complex a Real poskytnou operace relevatní typuReal jako Complex umožní typová konverze/přetížené operacefinal (Java), sealed (C#)String v JavěStream.flush a MemoryStream.flushclone () nebo readObject () v JavěThe one indisputable fact about multiple inheritance in C++ is that it opens up a Pandora's box of complexities that simply do not exist under single inheritance. – Scott Meyers
switchAnytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself. – Scott Meyers, Effective C++
switch (nebo ekvivalentní if) se dívejte s podezřením a přemýšlejte, zda není lepší ho nahradit polymorfismemclass Shape {
public void drawRectangle ();
public void drawShape ();
}
class Graphics {
public void drawShapes (Collection<Shape> shapes) {
for (Shape shape : shapes) {
draw (shape);
}
}
private void draw (Shape shape) {
if (shape.kind == ShapeKind.RECTANGLE) {
shape.drawRectangle ();
} else if (shape.kind == ShapeKind.CIRCLE) {
shape.drawCircle ();
} else {
throw new AssertionError ("unexpected shape: "+ shape.kind);
}
}
}
interface Shape {
public void draw ();
}
class Rectangle implements Shape {
public void draw () {
// draw rectangle
}
}
class Circle implements Shape {
public void draw () {
// draw circle
}
}
class Graphics {
public void drawShapes (Collection<Shape> shapes) {
for (Shape shape : shapes) {
shape.draw ();
}
}
}
interface Shape {
public void draw ();
}
class Rectangle implements Shape {
public void draw () {
// draw rectangle
}
}
class Circle implements Shape {
public void draw () {
// draw circle
}
}
class Graphics implements Shape {
Collection<Shape> shapes;
public void draw () {
for (Shape shape : shapes) {
shape.draw ();
}
}
}
Třída je immutable právě tehdy, pokud po vytvoření instance nejdou data instance žádným způsobem změnit.
private a final (Java)hashCode objektu se nesmí měnit, dokud je použit jako klíčBigInteger.negate()DateInterval postavený z mutable tříd Date
class DateInterval {
private Date begin;
private Date end;
// JE nutné používat defenzivní kopie.
public Date getBegin() { return begin.clone(); }
public Date getEnd() { return end.clone(); }
public DateInterval(Date begin, Date end) {
this.begin = begin.clone();
this.end = end.clone();
}
}
Date
Date date = new Date ();
Scheduler.scheduleTask (task1, date);
date.setTime (d.getTime() + ONE_DAY);
Scheduler.scheduleTask (task2, date);
DateInterval postavený z immutable tříd Date
class DateInterval {
private Date begin;
private Date end;
// NENÍ nutné používat defenzivní kopie.
public Date getBegin() { return begin; }
public Date getEnd() { return end; }
public DateInterval(Date begin, Date end) {
this.begin = begin;
this.end = end;
}
}
String vs. StringBuilderDimension vracená metodou Component.getSize ()
/**
* Class which stores information about timing of the experiments
* in the regression analysis.
*
* The class is immutable and especially Misho should never ever
* try to make it mutable :-)
*
* @author David Majda
*/
public class SchedulerInfo implements Serializable {
/* ... */
}