☰ Contents Classes that Share Behavior

Building Your Own Pict

Student: Ok, time to make my own Pict! Mine will be called Art, so it doesn’t collide with the real one that we have been using so far.
Prof: Good plan. Drawing is the hard part of Pict, so let’s skip it. Let’s just focus on the size of your Art. Write that as an interface, plus one simple record like the Rect from Pict.java.
Student: Wait, Block doesn’t have a width method. Did I need to write it?
Prof: Nope. Every record gets a method for each of its fields, with the same name. wall.width() is one of those, and it is what the interface asked for.
Student: Ok. So now I should add something like Beside. How about SideBySide?
Prof: Go ahead. What is the width of two pictures next to each other? What is the height?
Student: The widths add up, and the height is whichever is taller. And I want a nextTo method, like beside, so I don’t have to type new SideBySide(...).
Student: The last line is a SideBySide inside another SideBySide, and it still works.
Prof: Because left and right are Arts, not Blocks. It’s the same trick as And holding two ImageQuerys. Now one that holds a single picture: a Frame that adds a border, one unit thick on every side, around another Art.
Student: A frame of a frame is 4 wider, since each Frame asks the picture inside it for its width and adds 2.
Prof: Exactly, and the picture inside might itself be a Frame or a SideBySide. Each one only has to know about its own parts. That is the same design as ImageQuery and as the Pict library. It’s an interface that describes what every value can do, simple records, combinator records that hold other values of the interface, and default methods that build them.
Prof: Step through this one to watch each part get asked in turn:

Practice

Exercise 1. Stacked puts one picture on top of another, like Above in the Pict library. Fill in its width and its height.

interface Art {
int width();
int height();
}

record Block(int width, int height) implements Art {}

record Stacked(Art top, Art bottom) implements Art {
public int width() {
return ;
}
public int height() {
return ;
}
}

void main() {
System.out.println("All tests succeeded!");
}

Exercise 2. Finish Frame, which puts a border one unit thick around another picture, and the framed default method that builds it.

interface Art {
int width();
int height();

default Art framed() {
return ;
}
}

record Block(int width, int height) implements Art {}

record Frame(Art inner) implements Art {
public int width() {
return ;
}
public int height() {
return ;
}
}

void main() {
System.out.println("All tests succeeded!");
}