程序代写 COMPSCI4039: Programming

COMPSCI4039: Programming
Week 11 – Key Concepts Revision

What we will cover …

Copyright By PowCoder代写 加微信 powcoder

The revision lecture in Week 6 covered key concepts about classes, instances of those classes (objects), inheritance, arrays and looping.
I want to explain many of the key concepts within the second half of this course using simple examples:
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces,ArrayListsandGenerics
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion

What we will cover …
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces, Generics and ArrayLists
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion

Create and throw your own Exception …
● Create your own class that can be used as an exception by extending RuntimeException.
public class MyException extends RuntimeException { }
● This can be thrown by just creating an instance and using “throw”.
public class Throw {
public static void main(String[] args) {
System.out.println(“About to throw!”);
throw new MyException(); }

Java code may throw an Exception when something goes wrong …
● The random number may be greater than 10 … whereupon the array access will throw an OutOfBoundsException.
import java.util.Random; public class ArrayException {
public static void main(String[] args) { int[] x = new int[10];
Random r = new Random();
int pos = r.nextInt(20); System.out.println(x[pos]);

Code should really handle Exceptions to stop the program being terminated with an exception …
// Stops executing on a line an exception occurs.
}catch( ) {
// if code A causes an exception
}finally {
// some code done regardless

} catch(…) { …
} finally {
import java.util.Random;
public class ArrayExceptionCaught {
public static void main(String[] args) { int[] x = new int[10];
Random r = new Random();
int pos = r.nextInt(20); System.out.println(x[pos]); System.out.println(“This may not happen !”);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“Too big”);
e.printStackTrace();
}finally {
System.out.println(“This happens whatever”);

public class FR2 {
public static void main(String[] args) { FileReader fr = null;
String fN = “/Users/simon/Desktop/students.csv”; fr = new FileReader(fN);
}catch(FileNotFoundException e) { e.printStackTrace();
}finally { try {
if (fr != null) fr.close();
}catch(IOException e) {
e.printStackTrace();
A good example
of handling an exception generated by another method …

What we will cover …
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces,GenericsandArrayLists
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion

A class extends another class (inheritance) …
but a class can also implement many interfaces …
● A Dog class may extend an Animal class … whereupon an instance of the Dog class will inherit all the generic instance variables and methods that the Animal class has (i.e. getName(), getWeight(), getColour(), etc.)
● But Java only allows single inheritance … what happens if we also want to insist that 4-legged animals have a getSpeed() method ? We cannot inherit also from a FourLeggedAnimals class to get this functionality …
● This is where Java allows implementing interfaces to indicate classes have particular properties and need to implement particular methods.

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
● An interface that includes one method that is void and has no arguments.
● A class (Person) that implements the interface. It has the method (and could have others)
+ ” and I am ” + age + ” years
+ “ old.”); }
public class Dog extends Animal implements Greeter { // constructor and toString omitted
public void sayHello() {
System.out.println(“Woof!”);
● A Dog that can extend another class but also implements the Greeter interface (so needs to implement the sayHello method)

Can refer to an object using references to their class, superclass (inheritance) or any of their interfaces …
public class InterfaceTest {
public static void main(String[] args){
Person p = new Person(“Sam”, 45); Dog d = new Dog();
Animal aDog = new Dog();
Greeter a = new Person(Mary, 34); Greeter b = new Dog(); a.sayHello();
b.sayHello();
Creation of objects, but stored in reference of Greeter type
Important: when you store something in a superclass reference, or an interface reference, you can only access methods defined in the superclass or interface

What we will cover …
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces,GenericsandArrayLists
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion

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:
tells Java that the method has a generic type called ‘G’. We then use G as the type for the array argument.
public static void printArray(G[] array) { // Prints an array of objects for(int i=0;i { E firstAttribute;
E secondAttribute;
public GenericClass(E f, E g) { firstAttribute = f; secondAttribute = g;
Class uses generic data type E
public String toString(){
return( firstAttribute + “,\n” + secondAttribute);
Instance variables can have type E
Note parameter types in constructor!
You would create instances of this generic class using something like: GenericClass intPair = new GenericClass(6, 7);
GenericClass stringPair = new GenericClass(“Hello”, “World”);

Particular important example of a generic class is the ArrayList “container” class
import java.util.ArrayList; public class ArrayListExample {
public static void main(String[] args) { ArrayList myList = new 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();
Or strings …
… new ArrayList();

What we will cover …
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces, Generics and ArrayLists
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion

Adding components to a JFrame …
public class FlowLayoutDemo extends JFrame { private JButton button1, button2;
private JTextField textField1;
private JLabel label1;
public FlowLayoutDemo() {
this.setTitle(“Flow layout”);
this.setSize(500, 100); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); button1 = new JButton(“Ok”);
button2 = new JButton(“Quit”);
textField1 = new JTextField(“initial Text”, 15); label1 = new JLabel(“Click a button”);
this.setLayout(new FlowLayout()); this.add(button1); this.add(button2); this.add(label1); this.add(textField1);
This uses a FlowLayout …
Other layouts include: BorderLayout
GridLayout

What we will cover …
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces, Generics and ArrayLists
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers
b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion

ButtonFrame1
// import statements
public class ButtonFrame1 extends JFrame implements ActionListener { private JButton b = new JButton(“click me”);
public ButtonFrame1() {
// JFrame title, close and size
b.addActionListener(this);
this.add(b);
public void actionPerformed(ActionEvent e) { b.setText(“I was clicked.”);
// Main method — creates the ButtonFrame1 object

What we will cover …
1. Creating,ThrowingandCatchingExceptions.
2. Interfaces, Generics and ArrayLists
a. LayingoutGUIcomponents-JFrame,JPanelandLayoutManagers b. HandlingeventswithinGUIcomponents–ActionListener,ActionEvent
4. Recursion
To be discussed during the live session …

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com