Rohit Bajaj
asked on
What is the use of Forwarding Class in java
HI,
In Item16: Favor composition over inheritance in Joshua Bloch her mentions an example like :
I could have achieved the same using the following class :
I mean instead of using inheritance i could have still used composition by including the Set object inside the class directly...
Rather than implementing forwarding class etc...
What are the pros and cons of each of these approach ?
Thanks
In Item16: Favor composition over inheritance in Joshua Bloch her mentions an example like :
public class InstrumentedSet<E> extends ForwardingSet<E> {
private int addCount = 0;
public InstrumentedSet(Set<E> s) {
super(s);
}
@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;
}
}
// Reusable forwarding class
public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) { this.s = s; }
public void clear() { s.clear(); }
public boolean contains(Object o) { return s.contains(o); }
public boolean isEmpty()
public int size()
public Iterator<E> iterator()
public boolean add(E e)
public boolean remove(Object o)
public boolean containsAll(Collection<?> c)
{ return s.containsAll(c); }
public boolean addAll(Collection<? extends E> c)
{ return s.addAll(c); }
public boolean removeAll(Collection<?> c)
{ return s.removeAll(c); }
public boolean retainAll(Collection<?> c)
{ return s.retainAll(c); }
public Object[] toArray() { return s.toArray(); }
public <T> T[] toArray(T[] a) { return s.toArray(a); }
@Override public boolean equals(Object o)
{ return s.equals(o); }
@Override public int hashCode() { return s.hashCode(); }
@Override public String toString() { return s.toString(); }
}
I could have achieved the same using the following class :
public class InstrumentedSet<E> {
private Set set;
private int addCount = 0;
public InstrumentedSet(Set<E> s) {
set = s;
}
public boolean add(E e) {
addCount++;
return set.add(e);
}
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return set.addAll(c);
}
public int getAddCount() {
return addCount;
}
}
I mean instead of using inheritance i could have still used composition by including the Set object inside the class directly...
Rather than implementing forwarding class etc...
What are the pros and cons of each of these approach ?
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.