Top Banner
Java Programming Robert Chatley [email protected] William Lee [email protected]
38

Java Programming Robert Chatley [email protected] William Lee [email protected].

Dec 26, 2015

Download

Documents

Brendan Robbins
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Java Programming

Robert [email protected]

William [email protected]

Page 2: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Previous Experience

Page 3: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Course Outline Day 1 - Introduction

Java VM and Memory Model Java Object-Orientation Key language features

Day 2 - The standard library Collections and ADTs Using containers to store data Generics (new Java 1.5 features)

Page 4: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Course Outline

11 – 12 LEC LEC

12 – 1 LEC LEC

1 – 2

2 – 3 LAB LAB

3 – 4 LAB LAB

4 – 5 LEC LEC

Page 5: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Materials

http://www.doc.ic.ac.uk/~rbc/java

Page 6: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Compiling C++ Programs#include <stdio>main( int argc, char *argv[]) { // do something}

Page 7: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

The Java Virtual Machine

class Hello { public static void main(String[] args) { System.out.println( “Hello World” );}

Hello.java

…Method Hello() 0 aload_0 1 invokespecial #1 <Method java.lang.Object()> 4 returnMethod void main(java.lang.String[]) 0 getstatic #2 <Field java.io.PrintStream out> 3 ldc #3 <String "Hello World!"> 5 invokevirtual #4 <Method void println(String)> 8 return

Hello.class

javac

Page 8: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

The Java Virtual Machineclass Hello { public static void main() { // do something}

Mac JVM Linux JVM Win JVM

Hello.class

Hello.class

Hello.class

Page 9: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Platform Independence C++ compiles to native code for a

specific architecture (Linux, Windows…)

Java compiles to Java bytecode Same bytecode runs on virtual

machine for any platform Only VM is platform specific Good for downloadable code Applets etc

Page 10: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Memory Management (C++)

int main( int argc , char *[] argv ) {

Dog d(“rover”); Cat c(“fluffy”);

d.bark();

Dog *dp = new Dog(“sirius”);

dp->bark();

delete dp; }

C++ has two ways of creating objects

On the stack

(“automatic”)

On the heap (with new)Need to delete

Page 11: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Memory Management (C++)

int main( int argc , char *[] argv ) {

for( int i=0; i<100 ; i++ ) { Dog *dp = new Dog(“sirius”); dp->bark(); } }

Page 12: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Memory Management (Java)

public static void main( String[] args ) {

Dog d = new Dog(“rover”); Cat c = new Cat(“fluffy”);

d.bark();

Dog dp = new Dog(“sirius”);

dp.bark(); }

All Java objects are created on the heap

No stars or arrows

Page 13: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Memory Management (Java)

public static void main( String[] args ){

for( int i=0; i<100 ; i++ ) { Dog dp = new Dog(“sirius”); dp.bark(); } }

Java’s heap is garbage collected

Page 14: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Memory Management (Java)

public static void main( String[] args ){

for( int i=0; i<100 ; i++ ) { Dog dp = new Dog(“sirius”); dp.bark(); } }

Page 15: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

A First Program

class Hello {

public static void main( String[] args ) {

System.out.println(“Our first Java program”); }}

All programs must have at

least one class

At least one class must have a main method

with this signature

A standard library function to print text on

the console

Page 16: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Making it Run

Demo

Text Editor and Command Line Tools

Page 17: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Classpath The Classpath tells Java where to look

for classes Can be an environment variable or flag

to java(c) setenv CLASSPATH /homes/rbc/classes java A java –classpath /homes/rbc/classes A

Often include current dir (.) but can cause problems/confusion

Page 18: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

More Classes Programs comprise sets of classes Classes can have

Fields Methods Constructors

Page 19: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

A Dog Class

class Dog {

String name; int age;

Dog ( String p_name ) { name = p_name; }

void bark() { System.out.println(“Woof! Woof!”); }}

Field declaration

s

A constructor – NB no

destructor as Java has garbage

collection

Methods are defined inside

the class

Page 20: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

animals

Some other Animals

Dog

Abstract class

Group classes in a package

Cat Fish Bird

Animal

Page 21: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

animals

Some other Animals

Animal

Dog Cat Fish Bird

package animals;

abstract class Animal {

String name; int age;

public abstract void makeNoise();

}

abstract class

abstract method

package statement

Page 22: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

animals

Some other Animals

Animal

Dog Cat Fish Bird

package animals;

class Dog extends Animal {

Dog ( String p_name ) { name = p_name; }

public void makeNoise() { bark(); }

void bark() { System.out.println(“Woof! Woof!”); }}

implementing abstract method

inheritance – Dog extends

Animal

Page 23: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Using our Animals

import animals.*;

class PetShop {

public static void main( String[] args ) {

Animal pet = new Dog(“rover”); pet.makeNoise();

pet = new Bird(); pet.makeNoise(); }}

Import types defined in animals package

Creating an object with the new keyword

Page 24: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Access Modifiers

package animals;

public class Dog extends Animal {

public Dog ( String p_name ) { name = p_name; }

public void makeNoise() { bark(); }

private void bark() { System.out.println(“Woof! Woof!”); }}

Classes and methods accessed

from outside package must be

public

Methods called only in this

class should be private

Page 25: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Making it Run

Demo

Page 26: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Java has Single Inheritance

An Elephant is an Animal

A RingMaster is a Human

What if we want them both to be Performers?

Page 27: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Interfaces

ElephantRingMaster

Human AnimalPerformer

Inheritance -RingMaster

extends Human

Interface implementatio

n

Page 28: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Performer Interface

public interface Performer {

public void perform();

}

Interfaces define sets of

methods

Interfaces define

named types

No body for the method

given

Page 29: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Implementing the Interface

public class Elephant extends Animal implements Performer {

public void makeNoise() { trumpet(); }

public void perform() { walk(); trumpet(); }

} Implement method from

Performer

Declare class as

implementing interface

Page 30: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Using Performers

import animals.*;

class Circus {

public static void main( String[] args ) {

Performer p = new RingMaster(); p.perform();

p = new Elephant(); p.perform(); }}

Anything that implements

Performer may be assigned to p

Can only call methods from

Performer interface on p

Page 31: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Exceptions Sometimes a method may fail

Exceptional behaviour Catch and handle this special case

Methods can throw an Exception to signal that something is wrong

Page 32: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Documentation for FileReader

FileReader

public FileReader(File file) throws FileNotFoundException

Creates a new FileReader, given the File to read from.

Parameters:

file - the File to read from

Throws:

FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

Page 33: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Try and Catchclass Test {

public void readFile() {

File myFile = new File( “data.txt” );

try {

FileReader fr = new FileReader( myFile );

} catch ( FileNotFoundException fnfe ) {

System.out.println( “File not found.” );

} }}

Page 34: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Things to do in Catch

class Test {

} catch ( FileNotFoundException fnfe ) {

System.err.println( “File not found.” );

System.err.println( fnfe.getMessage() );

fnfe.printStackTrace();

} }}

Page 35: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Alternatively, Throwclass Test {

public void readFile() throws FileNotFoundException {

File myFile = new File( filename );

FileReader fr = new FileReader( myFile );

}}

Page 36: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Throwing your own exceptions

class Test {

public void unlockDoor() throws AlreadyOpenException {

if ( open ) {

throw new AlreadyOpenException();

}}

class AlreadyOpenException extends Exception {}

Page 37: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

…and Finallypublic void readFile( filename ) {

File myFile = new File( filename ); FileReader fr = new FileReader( myFile );

try {

int i = fr.read();

} catch ( IOException ioe ) { System.err.println( “Error reading file” ); } finally {

try { if ( fr != null ) fr.close(); } catch ( IOException ioe ) { System.err.println( “Error closing stream” ); } }}

Page 38: Java Programming Robert Chatley rbc@doc.ic.ac.uk William Lee wwhl@doc.ic.ac.uk.

Today’s lab : 2-4pm Rm 219

JeffreyMarkus

Helpers Writing a program using fundamental Java concepts

Using the tools from the Java Development Kit