Delegation
solidCuboid.mass()
↓
SolidCuboid receives the call
↓
SolidCuboid forwards the request
↓
SolidImpl.mass()
↓
result returned back
SolidCuboid, SolidSphere, and SolidImpl all implements Solid. It’s just that SolidCuboid and SolidSphere both have a mass() method. So they outsource that to SolidImpl.
SolidImpl IS-A Shape3D SolidImpl HAS-A Shape3D This is a common pattern for delegation.
More on delegation
Solid (Interface)
interface Solid {
double mass();
}
SolidImpl (Class) (Shared Implementation with SolidSphere to Solid)
class SolidImpl implements Solid {
private final Shape3D shape;
private final double density;
SolidImpl(Shape3D shape, double density) {
this.shape = shape;
this.density = density;
}
@Override
public double mass() {
return shape.volume() * density;
}
}
SolidSphere (Class) (Shared Implementation with SolidImpl to Solid)
class SolidSphere extends Sphere implements Solid {
private final SolidImpl solid;
SolidSphere(double radius, double density) {
super(radius);
this.solid = new SolidImpl(this, density);
}
@Override
public double mass() {
return solid.mass();
}
@Override
public String toString() {
return "solid-" + super.toString() +
" with a mass of " +
String.format("%.2f", mass());
}
}
Explanation So i needed to outsource the work to SolidImpl class, That’s why my mass() is just a simple solid.mass() I still defined mass() in solidcuboid because I implemented Solid (an interface with the mass() function) I implemented solid because I wanted to implement the same thing that the SolidImpl class implemented.