COMPSCI4039: Programming
COMPSCI4039: Programming
Interfaces, generics, ArrayLists
Copyright By PowCoder代写 加微信 powcoder
Interfaces
Remember objects and inheritance? We said:
Interfaces: Interfaces define a set of methods. Any class that implements the interface must have these methods in it
In Java, any class can only extend one other class but your class can implement as many interfaces as you like
We need interfaces now, to make GUIs do things
We saw an example of an interface (Comparable) when sorting arrays
What is an interface?
An interface is a set of one or more method signatures
Any class that implements the interface has to implement all the methods
It is a formal way of telling Java that a class has certain functionality
Any objects from a class that implements an interface can be stored in a reference of the type of the interface
An example…
An interface that includes one method that is void and has no arguments.
public interface Greeter {
public void sayHello();
public class Person implements Greeter {
// constructor and toString omitted
public void sayHello() {
System.out.println(“Hi, I’m ” + name
+ ” and I am ” + age + ” years
+ “ old.”);
public class Dog implements Greeter {
// constructor and toString omitted
public void sayHello() {
System.out.println(“Woof!”);
A class (Person) that implements the interface. It has the method (and could have others)
And another (Dog)
public class IntTest {
public static void main(String[] args){
Person p = new Person(“Sam”, 45);
Greeter a = new Person(Mary, 34);
Greeter b = new Dog();
a.sayHello();
b.sayHello();
Greeter[] aa = new Greeter[3];
aa[0] = new Dog();
aa[1] = new Dog();
aa[2] = new Person();
for(int i=0;i<3;i++) {
aa[i].sayHello();
Normal creation (to show you still can)
Creation of objects, but stored in reference of Greeter type
Allows you to refer to (or group) objects based on shared functionality
Important: when you store something in an interface reference, you can only access methods defined in the interface (this doesn’t include the toString method - see next slide)
Object methods
The reason we can access the toString method in Dog and Person for objects stored as Greeter type (but not - if there were any - other methods) is the following:
“Each interface implicitly declares one method for each public method in Object”.
This includes toString, equals and getClass
You don’t have to re-implement them, but you can
Comparable revisited - Orderable
[note: this is *my* version of Comparable. The Java one is better, but this helps us illustrate interfaces]
public class Sorting {
public static void sort(Orderable[] array) {
* Bubble sort for *any* array of
* type Orderable
boolean anyChanged = true;
while(anyChanged) {
anyChanged = false;
for(int i=0;i
return true;
return false;
Here’s another example
One car is ‘bigger’ than another if it has a higher maximum speed
public class Car implements Orderable{
private double maxSpeed;
public Car(double m) {
this.maxSpeed = m;
public String toString() {
return “Max speed is ” + this.maxSpeed;
public double getSpeed() {
return this.maxSpeed;
public boolean isBiggerThan(Orderable other) {
Car otherCar = (Car)other;
if(this.maxSpeed > otherCar.getSpeed()) {
return true;
return false;
import java.util.Random;
public class SortExample {
public static void main(String[] args) {
Number[] a = new Number[10];
Random r = new Random();
System.out.println(“Unsorted”);
for(int i=0;i<10;i++) {
a[i] = new Number(r.nextInt(100));System.out.print(a[i] + " ");
System.out.println();System.out.println("Sorted");
Sorting.sort(a);
for(int i=0;i<10;i++) { System.out.print(a[i] + " ");}
System.out.println();
Car[] b = new Car[5];System.out.println("Unsorted");
for(int i=0;i<5;i++) {
b[i] = new Car(r.nextDouble()*200.0);System.out.println(b[i]);
System.out.println("Sorted");
Sorting.sort(b);
for(int i=0;i<5;i++) { System.out.println(b[i]);}
Sorting the Number array
Sorting the Car array
With our Orderable interface, we can store anything that implements the interface (can be ordered) as the same type...
...so we only need one bit of code to sort.
By implementing the interface we are telling Java (and other coders) something our objects can do (in this case, compare themselves with others)
Within the sort method we wouldn’t be able to use any methods specific to Number or Car - we can only use things defined in Orderable.
But we don’t need anything else when we’re in the sort method...
COMPSCI4039: Programming
Interfaces, generics, ArrayLists
Making GUIs do things: the ActionListener interface
When a user does something in a Swing GUI (e.g. click a button) an ActionEvent is created (automatically by Swing).
ActionEvents are processed by methods called actionPerformed
If you want something to happen when a button is pressed, you need to assign an object to the button that has an actionPerformed method
ActionListener is the interface that defines actionPerformed
Any class that implements ActionListener can be assigned as the listener for any component.
A GUI with action
We will build a simple GUI
A single frame:
One JTextField
One JButton
When JButton is pressed, text in JTextField should change
Code without action
Class extends JFrame
Components are declared and placed inside a JPanel
JPanel is placed inside the JFrame
main method creates an instance of the class
Nothing happens when the button is pressed because we haven’t told it which ActionListener to use
public class NoAction extends JFrame {
JTextField text;
JButton press;
public NoAction() {
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
text = new JTextField("Not pressed yet");
panel.add(text);
press = new JButton("Press me");
panel.add(press);
this.add(panel);
this.setVisible(true);
public static void main(String[] args) { new NoAction();}
...with action
public class Action extends JFrame implements ActionListener{
JTextField text;
JButton press;
public Action() {
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
text = new JTextField("Not pressed yet");
panel.add(text);
press = new JButton("Press me");
press.addActionListener(this);
panel.add(press);
this.add(panel);
this.setVisible(true);
public void actionPerformed(ActionEvent e) {
text.setText("Pressed!");
public static void main(String[] args) { new Action();}
Write an actionPerformed method to include what we want to happen when the JButton is pressed
Tell Java that this class can be used as an ActionListener
Add this class itself as the ActionListener for the JButton (could also use another class)
Interfaces describe functionality
Through a bunch of methods
Objects from classes that implement an interface can be stored in a reference of the interface type
We saw that with ActionListener.
Look at the signature for addActionListener (a method that we call to add a listener to the JButton):
public void addActionListener(ActionListener l)
We can pass our JFrame object because it implements ActionListener (and can therefore be stored in an ActionListener reference.
You’ll see a lot more examples of this later this week
COMPSCI4039: Programming
Interfaces, generics, ArrayLists
Comparable is a Java interface that formalises comparisons between objects
We saw it in use for sorting arrays
Arrays of any type could be sorted if the class implemented Comparable
Remember this slide for a Comparable Student class?
public class Student implements Comparable{
private int grade;
private String name;
public Student(String n,int g) {
grade = g;
public int getGrade() {return grade;}
public int compareTo(Object o) {
if(o instanceof Student) {
Student other = (Student)o;
if(this.getGrade() > other.getGrade()) {
}else if(this.getGrade() < other.getGrade()) {
return -1;
A comparable student
We use implements to tell that this class implements the Comparable interface.
We write our own compareTo method which takes the object to be compared with as an argument. It should return 1 if the current object should be later in the list than the other object. -1 if earlier, and 0 if equal.
Note: compareTo takes an Object argument. It could therefore be anything. We have to check first that it is a Student.
instanceof
Because Comparable took an argument of type Object it could, in theory, be passed anything.
We had to check that the Object was actually a Student:
if(o instanceof Student)
Feels clumsy...but interfaces define method signatures and signatures define argument types. By defining the type as object, anything can be passed.
public int compareTo(Object o)
Generics let us overcome this...
Another Comparable interface
Here’s Student2, that uses a different interface
This interface uses generics
The interface is given a type (Student2)
Which is then the argument to the compareTo method
No longer need to check the type of the argument
public class Student2 implements Comparable
private int grade;
private String name;
public Student2(String n,int g) {
grade = g;
public int getGrade() {return grade;}
public int compareTo(Student2 o) {
if(this.getGrade() > o.getGrade()) {
}else if(this.getGrade() < o.getGrade()) {
return -1;
Comparable
The generic Comparable interface will look something like this:
public interface Comparable
public int compareTo(E o);
The ‘E’ is a type that gets defined when the user implements the interface
When the interface is implemented whatever is substituted for ‘E’ at the top, will be substituted everywhere:
public class Student2 implements Comparable
public int compareTo(Student2 o)
Methods can be generic
Generics allow us to write methods that can take arguments of any type
This prints an array, regardless of the arrays type:
public static
// Prints an array of
for(int i=0;i
…and classes
public class GenericClass
E firstAttribute;
E secondAttribute;
public GenericClass(E f, E g) {
firstAttribute = f;
secondAttribute = g;
public String toString(){
return( firstAttribute + “,\n” + secondAttribute);
Class has generic type E
Instance variables can have type E
This toString method assumes E
has toString method (or default)
Note parameter types in constructor!
Testing the generic class
Person, Dog, Circle simplified versions of classes you’ve seen before
Each have a constructor and toString method
Person and Dog implement the Greeter interface
Code on next slide is inside main method of tester class (testGen)
Testing the Generic Class contd.
Person person1 = new Person(“Morag”,25); Person person2 = new Person(“Wilf”,75);
Dog dog1 = new Dog(); Dog dog2 = new Dog();
Circle circle1 = new Circle(3); Circle circle2 = new Circle(6);
GenericClass
System.out.println(myGenClassP);
GenericClass
System.out.println(myGenClassD);
GenericClass
System.out.println(myGenClassC);
GenericClass
System.out.println(myGenClassG1);
GenericClass
System.out.println(myGenClassG2);
Three different instantiations of GenericClass, each with a different type
.. and two with type Greeter
See TestGen.java in folder containing week7 files
COMPSCI4039: Programming
Interfaces, generics, ArrayLists
The ArrayList class
An arraylist is an object that we can use much like an array
Can be used to store objects – but not elements of primitive type!*
Unlike an array it grows to accommodate additional items (even if an initial size is specified)
It is a generic class. So
It has <> notation
when instantiated a type must be specified
* but we can overcome this by using the wrapper classes:
e.g. Integer, Character and Boolean.
You saw Integer class in Objects2 lectures (week 3).
Other wrapper classes are similar – they allow you to treat an element of primitive type as an object and take advantage of useful methods.
Take a look in the Java API for ArrayList here https://docs.oracle.com/javase/7/docs/api/
Have to import from java.util
It has three constructors and lots of methods
We will only use a few of these.
Constructors:
ArrayList() – constructs an empty list with initial capacity 10
ArrayList(int init) – constructs an empty list with intial capacity init
Some ArrayList methods
Return type method
boolean add(E e) : appends the specified element to the end of list.
void add(int index, E element) : inserts specified element at specified position in list.
void clear() : removes all the elements from list
boolean contains(Object o) : returns true if list contains the specified element.
E get(int index) : returns the element at the specified position in list.
boolean isEmpty() : returns true if list contains no elements.
int size() : returns the number of elements in list
E remove(int index) : Removes the element at the specified position in list.
ArrayList example
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList
Person person1 = new Person(“Agnes”, 30);
Person person2 = new Person(“Aretha”, 29);
Person person3 = new Person(“Adam”, 42);
Person person4 = new Person(“Arnold”, 60);
Person person5 = new Person(“Alexander”, 30);
myList.add(person1); myList.add(person2); myList.add(person3);
myList.add(person4); myList.add(person5);
int n = myList.size();
System.out.println(“This list has size ” + n); //5
for(int i = 0; i
myList.add(1); myList.add(2); myList.add(3);
int sum = 0;
for(Integer i : myList) sum+=i;
System.out.println(“The arrayList sum is ” + sum);
// illustrating for each loop with an array
int[] myArray = new int[10];
myArray[0] = 1; myArray[1] = 2; myArray[2] = 3;
int sum2 = 0;
for(int i : myArray) sum2+=i;
System.out.println(“The array sum is ” + sum2);
The arrayList sum is 6
The array sum is 6
Integer wrapper class used …
… but ints added wrapper class automatically converts to Integer (called “boxing”)
for each loops
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com