Suppose you want to create simple class that prints greeting with any name:
public class Greeting {
private final String name;
public Greetings(String name) {
this.name = name;
}
public void printHello() {
System.out.println("Hello " + name + "!");
}
}
When you pass String s = "World"
, the result would be "Hello World!"
. This way, you can change the behaviour of the Greeting
class. If Greeting
class would look like this:
public class Greeting {
public void printHello() {
System.out.println("Hello java!");
}
}
There would not be any option how to change this greeting.
The same applies for classes Artframe
and Drawing
. Artframe
just displays what you provide.
Note, that following code snippets would not compile, since they use non-existing graphics context, methods, ...
interface Drawing {
void paintTo(Canvas c);
}
class Artframe extends JFrame {
Drawing drawing;
public Artframe(Drawing drawing) {
this.drawing = drawing;
}
protected void paint(Canvas c) {
drawing.paintTo(c);
}
}
Drawing can be implemented in various ways e. g. one implementation draws to graphics context circle, other draws rectangle, ....
public CircleDrawing implements Drawing {
Point centerPoint = new Point(0,0);
int radius = 5;
int strokeWidth = 1;
public void paintTo(Canvas c) {
c.drawCircle(centerPoint, radius, strokeWidth);
}
}
public RectangleDrawing implements Drawing {
Point topLeft = new Point(0,0);
Dimension dim = new Dimension(100, 50);
int strokeWidth = 1;
public void paintTo(Canvas c) {
c.drawRect(topLeft , dim, strokeWidth);
}
}
To display circle in Artframe
you just have to pass CircleDrawing
instance:
new Artframe(new CircleDrawing());
If you need to display rectangle, then:
new Artframe(new RectangleDrawing());
Again, if your Artframe
class would not have Drawing
dependency, i. e. used drawing would be hard-coded into the Artframe
, then you would not be able to change it's behaviour - displayed would always be the same Drawing
:
class Artframe extends JFrame {
Drawing drawing = new RectangleDrawing();
protected void paint(Canvas c) {
drawing.paintTo(c);
}
}