Interfaces
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
June 2, 2025
public interface ...
” is used instead of “public class ...
” at the beginning of the file.public
.Readable
interface declares a read()
method, which returns a String-type object.TextMessage
that implements the Readable
interface.TextMessage
class implements the Readable
interface (public class TextMessage implements Readable
), the TextMessage
class must contain an implementation of the public String read()
method.Reader
implementationsTextMessage
class, let’s add another class that implements the Readable
interface.Ebook
class is an electronic implementation of a book that containing the title and pages of a book.public String read()
method always returns the next page as a string.public class Ebook implements Readable {
private String name;
private ArrayList<String> pages;
private int pageNumber;
public Ebook(String name, ArrayList<String> pages) {
this.name = name;
this.pages = pages;
this.pageNumber = 0;
}
public String getName() {
return this.name;
}
public int pages() {
return this.pages.size();
}
public String read() {
String page = this.pages.get(this.pageNumber);
nextPage();
return page;
}
private void nextPage() {
this.pageNumber = this.pageNumber + 1;
if(this.pageNumber % this.pages.size() == 0) {
this.pageNumber = 0;
}
}
}
TextMessage message = new TextMessage("mina", "It's going great!");
System.out.println(message.read());
ArrayList<TextMessage> textMessage = new ArrayList<>();
textMessage.add(new TextMessage("private number", "I hid the body.");
Sample Output
Ebook
objectArrayList<String> pages = new ArrayList<>();
pages.add("Split your method into short, readable entities.");
pages.add("Separate the user-interface logic from the application logic.");
pages.add("Always program a small part initially that solves a part of the problem.");
pages.add("Practice makes the master. Try different out things for yourself and work on your own projects.");
Ebook book = new Ebook("Tips for programming.", pages);
int page = 0;
while (page < book.pages()) {
System.out.println(book.read());
page = page + 1;
}
Sample Output
TacoBox
ready for your use.int tacosRemaining()
return the number of tacos remaining in the box.void eat()
reduces the number of tacos remaining by one. The number of tacos remaining can’t become negative.TripleTacoBox
, that implements the TacoBox
interface.
TripleTacobox
has a constructor with no parameters.TripleTacobox
has an object variable tacos
which is initialized at 3 when the constructor is called.CustomTacoBox
, that implements the TacoBox
interface.
CustomTacoBox
has a constructor with one parameter defining the initial number of tacos in the box(int tacos
).String string = "string-object";
TextMessage message = new TextMessage("mina", "many types for the same object");
Ebook
class that implements the Readable
interface is both Ebook
and Readable
.TextMessage
class implements the Readable
interface, it has a Readable
type in addition to the TextMessage
type.Readable
tooEbook
class that implements the Readable
interface is both Ebook
and Readable
.ArrayList<Readable> readingList = new ArrayList<>();
readingList.add(new TextMessage("mina", "never been programming before..."));
readingList.add(new TextMessage("mina", "gonna love it i think!"));
readingList.add(new TextMessage("mina", "give me something more challenging! :)"));
readingList.add(new TextMessage("mina", "you think i can do it?"));
readingList.add(new TextMessage("mina", "up here we send several messages each day"));
ArrayList<String> pages = new ArrayList<>();
pages.add("A method can call itself.");
readingList.add(new Ebook("Introduction to Recursion.", pages));
for (Readable readable: readingList) {
System.out.println(readable.read());
}
Ebook
class that inherits the Readable
interface class is always of the interface’s type, not all classes that implement the Readable
interface are of type Ebook
.Ebook
class to a Readable
-type variable, but it does not work the other way without a separate type conversion.Readable readable = new TextMessage("mina", "TextMessage is Readable!"); // works
TextMessage message = readable; // doesn't work
// works if, and only if, readable is of text message type
TextMessage castMessage = (TextMessage) readable;
equals
method.print
method in the Printer
class of the class below gets a variable of type read
.public class Printer {
public void print(Readable readable) {
System.out.println(readable.read());
}
}
print
method of the printer
class lies in the fact that it can be given any class that implements the Readable
interface as a parameter.Readable
class, the method would function as desired.print
method exampleTextMessage message = new TextMessage("mina", "Oh wow, this printer knows how to print these as well!");
ArrayList<String> pages = new ArrayList<>();
pages.add("Values common to both {1, 3, 5} and {2, 3, 4, 5} are {3, 5}.");
Ebook book = new Ebook("Introduction to University Mathematics.", pages);
Printer printer = new Printer();
printer.print(message);
printer.print(book);
ReadingList
to which we can add interesting things to read.ArrayList
instance as an instance variable, where the things to be read are added.add
method, which receives a Readable
-type object as its parameter.ReadingList
also implements Readable
ReadingList
class implement the Readable
interface.read
method of the reading list reads all the objects in the readables
list, and adds them to the string returned by the read()
method one-by-one.public class ReadingList implements Readable {
private ArrayList<Readable> readables;
public ReadingList() {
this.readables = new ArrayList<>();
}
public void add(Readable readable) {
this.readables.add(readable);
}
public int toRead() {
return this.readables.size();
}
public String read() {
String read = "";
for (Readable readable: this.readables) {
read = read + readable.read() + "\n";
}
// once the reading list has been read, we empty it
this.readables.clear();
return read;
}
}
ReadingList
classReadingList mikesList = new ReadingList();
mikesList.add(new TextMessage("arthur", "have you written the tests yet?"));
mikesList.add(new TextMessage("arthur", "have you checked the submissions yet?"));
System.out.println("Mike's to-read: " + mikesList.toRead());
ReadingList
is of type Readable
, we’re able to add ReadingList
objects to the reading list.ReadingList
to the ReadingList
classReadingList mikesList = new ReadingList();
int i = 0;
while (i < 1000) {
mikesList.add(new TextMessage("arthur", "have you written the tests yet?"));
i = i + 1;
}
System.out.println("Mike's to-read: " + mikesList.toRead());
System.out.println("Delegating the reading to Berny");
ReadingList bernysList = new ReadingList();
bernysList.add(mikesList);
bernysList.read();
System.out.println();
System.out.println("Mike's to-read: " + mikesList.toRead());
The read
method called on Berny’s list goes through all the Readable
objects and calls the read
method on them.
When the read
method is called on Berny’s list it also goes through Mike’s reading list that’s included in Berny’s reading list.
Mike’s reading list is run through by calling its read
method.
At the end of each read
method call, the read list is cleared.
In this way, Mike’s reading list empties when Berny reads it.
As you notice, the program already contains a lot of references.
It’s a good idea to draw out the state of the program step-by-step on paper and outline how the read
method call of the bernysList
object proceeds!
<<interface>>
NameOfTheInterface.
Readable
and its implementationsPackable
to your program.Book
and CD
, which implement the Interface.
Book
has a constructor which is given the author (String), name of the book (String), and the weight of the book (double) as parameters.CD
has a constructor which is given the artist (String), name of the CD (String), and the publication year (int).Packable
in both of the classes.public static void main(String[] args) {
Book book1 = new Book("Fyodor Dostoevsky", "Crime and Punishment", 2);
Book book2 = new Book("Robert Martin", "Clean Code", 1);
Book book3 = new Book("Kent Beck", "Test Driven Development", 0.5);
CD cd1 = new CD("Pink Floyd", "Dark Side of the Moon", 1973);
CD cd2 = new CD("IU", "The Winning", 2024);
CD cd3 = new CD("Daft Punk", "Random Access Memories", 2013);
System.out.println(book1);
System.out.println(book2);
System.out.println(book3);
System.out.println(cd1);
System.out.println(cd2);
System.out.println(cd3);
}
Output
Fyodor Dostoevsky: Crime and Punishment
Robert Martin: Clean Code
Kent Beck: Test Driven Development
Pink Floyd: Dark Side of the Moon (1973)
IU: The Winning (2024)
Daft Punk: Random Access Memories (2013)
Box
. Items implementing the Packable
interface can be packed into a box.Box
constructor takes the maximum capacity of the box in kilograms as a parameter.public static void main(String[] args) {
Box box = new Box(10);
box.add(new Book("Fyodor Dostoevsky", "Crime and Punishment", 2)) ;
box.add(new Book("Robert Martin", "Clean Code", 1));
box.add(new Book("Kent Beck", "Test Driven Development", 0.7));
box.add(new CD("Pink Floyd", "Dark Side of the Moon", 1973));
box.add(new CD("IU", "The Winning", 2024));
box.add(new CD("Daft Punk", "Random Access Memories", 2013));
System.out.println(box);
}
double weight
in the Box
class, replace it with a method which calculates the weight of the box:public class Box {
//...
public double weight() {
double weight = 0;
// calculate the total weight of the items in the box
return weight;
}
}
Packable
Interface requires a class to have the method double weight()
.Box
packable as well!packable
Interface.Factory
that can be asked to construct different objects that implement the Packable
interface.import java.util.Random;
public class Factory {
public Factory() {
// Note that there is no need to write an empy constructor without
// parameters if the class doesn't have other constructors.
// In these cases Java automatically creates a default constructor for
// the class which is an empty constructor without parameters.
}
public Packable produceNew() {
// The Random-object used here can be used to draw random numbers.
Random ticket = new Random();
// Draws a number from the range [0, 4). The number will be 0, 1, 2, or 3.
int number = ticket.nextInt(4);
if (number == 0) {
return new CD("Pink Floyd", "Dark Side of the Moon", 1973);
} else if (number == 1) {
return new CD("IU", "The Winning", 2024);
} else if (number == 2) {
return new Book("Robert Martin", "Clean Code", 1);
} else {
return new Book("Kent Beck", "Test Driven Development", 0.7);
}
}
}
Factory
can be used without exactly knowing what different kind of Packable
classes exist.Packer
that gives a box of things.Packable
, one can add new classes that implement the interface without changing the packer.ChocolateBar
.Packer
works without changes with the updated version of the factory.Factory
class modifiedimport java.util.Random;
public class Factory {
// Because Java's automatically generated default constructor is enough,
// we don't need a constructor
public Packable produceNew() {
Random ticket = new Random();
int number = ticket.nextInt(5);
if (number == 0) {
return new CD("Pink Floyd", "Dark Side of the Moon", 1973);
} else if (number == 1) {
return new CD("Daft Punk", "Random Access Memories", 2013);
} else if (number == 2) {
return new Book("Robert Martin", "Clean Code", 1 );
} else if (number == 3) {
return new Book("Kent Beck", "Test Driven Development", 0.7);
} else {
return new ChocolateBar();
}
}
}
Packer
does not depend on the classes that implement the Packable
interface.Packer
class.Packable
classes doesn’t affect the classes that use the Packer
class.List
and Set
interfaces implement the Collection
interface.Collection
interface provides, for instance, methods for checking the existence of an item (the method contains
) and determining the size of a collection (the method size
).Collection
interface also determines how the collection is iterated over.Collection
interface, either directly or indirectly, inherits the functionality required for a for-each
loop.List
interface, one can also use it through the List
interface.List<String> strings = new ArrayList<>();
strings.add("string objects inside an arraylist object!");
List
, there are many classes that implement the List
interface.List
interface exactly the same way as an object created from ArrayList.ArrayList
s and LinkedList
sList
interface work the same way.ArrayList
and LinkedList
differ quite a bit.
ArrayList
saves objects to an array where fetching an object with a specific index is very fast.LinkedList
constructs a list where each element contains a reference to the next element in the list.Set
InterfaceHashSet
in no way assumes the order of a set of elements.equals
and hashCode
methods defined.int
, double
, boolean
)ArrayList
)Print
and Scanner
)public class Life {
public static void main(String[] args) {
// Variable to control if we are learning
boolean learning = true;
// While loop to represent the continuous learning process
while (learning) {
System.out.println("Experimenting with new concepts and ideas...");
System.out.println("Making mistakes and learning from them...");
System.out.println("Learning from experiences...");
}
}
}
Computer Language