Вы находитесь на странице: 1из 127

Programming in Java

Introduction

Java Features
y Java
no pointers Is interpreted (C/C++ are Compiled) No Preprocessor No #define, #ifdef, #include, Concurrent Lots of Libraries Internet applications Runs on the client side Portable Secure Event Driven Easy to Learn

Example
y Hello Class Program
public class Hello { public static void main(String argv[]) { System.out.println(Hello Class"); System.exit(0); } }

y main has a return type of void (not int)


y The System.exit method is used to return value back to OS

y System.out.println is a print statement.

Compile/Execute
y The file name should be same as class name y There can be multiple classes in the same file (For now, let us consider one class per file) y Class is same as an Object y javac <filename> compiles the java code File name has a .java extension eg. Hello.java y It produces a class file (contains java byte code for Java Virtual Machines JVM). Eg. Hello.class y java <filename without .class> executes the program
4

Other Utilities
y javap -package java.lang.Integer lists the methods and variables that are available in the package java.lang.Integer. y javap -c <classname>. Produces a byte code of your program. Bytecode is written in Java Virtual Machine. y Javadoc <filename> produces a HTML file which is a documentation of your program. One can see the documentation using a browser.

Names and Types


variables functions, methods classes or Objects Types of variables - int, float, double, boolean Arrays (unlike C or C++, in Java arrays are treated as an Object.) y Life time of a variable y y y y y

Types of Methods and Variables


y y y y y Instance variable. Instance methods Static variables and Static Methods public, private and protected variables and methods Constructor Method Automatic Variables

Import
y Import Statement
Without an import statement
java.util.Calendar c1;

After the import statement


import java.util.Calendar; ... Calendar c1;

Saves typing
import java.util.*; // Imports all classes

Examples
public class fact { public static int factorial(int n) { if (n==0) return 1 else return n * factorial(n-1); } public static void main(String argv[]) { int x; x=9; System.out.println(Factorial of +x+ is +factorial(x));

Expressions
y Arithmetic expressions in Java are similar to C/C++
y Example
int i = 5 + 12 / 5 - 10 % 3 = 5 + (12 / 5) - (10 % 3) =5+2-1 =6

Operators cannot be overloaded in Java Integer division vs. floating point division Operator precedence

10

Objects
y Objects
y Instances of classes are called objects y Object variables store the address of an object
Different from primitive variables (which store the actual value) Primitive Data Type example
int i=3; int j=i; i=2; // i==2; j==3

Object Example1
java.awt.Button b1 = new java.awt.Button("OK"); java.awt.Button b2 = b1; b2.setLabel("Cancel"); // Change is visible via b1 also b1 = new java.awt.Button("Cancel")

y No explicit dereferencing (i.e., no &, * or -> operators)


No pointers null = "Absence of reference" = a variable not pointing to an object
11

Programming in Java
Objects, Classes, Program Constructs

12

Program Structure/Environment
y Java
Is interpreted (C/C++ are Compiled) No Preprocessor No #define, #ifdef, #include, ...

y Main method (for Java applications)


Embedded in a Class
public class Xyz { public static void main (String args[]) { } }

Each class can define its own main method Programs starting point depends on how the interpreter is invoked.
$ java Xyz

13

Command Line Arguments


y Command Line Args are passed to main method
public class Echo { public static void main(String argv[]) { for (int i=0; i<argv.length; i++) System.out.print(argv[i] + ); System.out.print("\n"); System.exit(0); } }

y main has a return type of void (not int)


y The System.exit method is used to return value back to OS

y The length property is used to return array size

14

For Statement
y Javas for stmt is similar to C/C++, except:
y Comma operator is simulated in Java
for (i=0, j=0; (i<10) && (j<20); i++, j++) { }

Allowed in initialization and test sections Makes Java syntactically closer to C

y Variable declaration
variables can be declared within for statement, but cant be overloaded
int i; for (int i=0; i<n; i++) { } // Not valid in Java

declaration is all or nothing


for (int i=0, j=0; ) // Declares both i and j

y Conditional must evaluate to a boolean


Also true for if, while
15

If, While, Do While, Switch


y These are (essentially) the same as C/C++
if (x != 2) y=3; if (x == 3) y=7; else y=8; if (x >= 4) { y=2; k=3; } while (x<100) { System.out.println ("X=" + x); x *= 2; } do { System.out.println ("X=" + x); x *= 2; } while(x<100); char c; ... switch (c) { case 'Q': return; case 'E': process_edit(); break; default: System.out.println ("Error"); }

16

Name Space
y No globals
y variables, functions, methods, constants

y Scope
y Every variable, function, method, constant belongs to a Class y Every class is part of a Package

y Fully qualified name of variable or method


<package>.<class>.<member>

Packages translate to directories in the class path A package name can contain multiple components
java.lang.String.substring() COM.Ora.writers.david.widgets.Barchart.display() - This class would be in the directory XXX/COM/Ora/writers/david/widgets, where XXX is a directory in the class path

17

Package; Import
y Package Statement
Specifies the name of the package to which a class belongs
package Simple_IO; // Must be the first statement public class Reader { }

Optional

y Import Statement
Without an import statement
java.util.Calendar c1;

After the import statement


import java.util.Calendar; ... Calendar c1;

Saves typing
import java.util.*; // Imports all classes
18

Access Rules
y Packages are accessible
If associated files and directories exist and have read permission

y Classes and interfaces of a package are accessible


From any other class in the same package Public classes are visible from other packages

y Members of a class (C) are accessible


[Default] From any class in the same package Private members are accessible only from C Protected members are accessible from C and subclasses of C Public members are accessible from any class that can access C

y Local variables declared within a method


Are not accessible outside the local scope

19

Data Types
y Primitive Types
y Integral (byte, short, char , int, long)
char is unsigned and also used for characters

y Floating Point (float, double) y boolean

y Classes
y Predefined classes
String, BigInteger, Calendar, Date, Vector, ... Wrapper classes (Byte, Short, Integer, Long, Character)

y User defined classes y "Special" classes


Arrays
20

Objects
y Objects
y Instances of classes are called objects y Object variables store the address of an object
Different from primitive variables (which store the actual value) Primitive Data Type example
int i=3; int j=i; i=2; // i==2; j==3

Object Example1
java.awt.Button b1 = new java.awt.Button("OK"); java.awt.Button b2 = b1; b2.setLabel("Cancel"); // Change is visible via b1 also b1 = new java.awt.Button("Cancel")

y No explicit dereferencing (i.e., no &, * or -> operators)


No pointers null = "Absence of reference" = a variable not pointing to an object
21

Objects are handled by Reference


y Objects in Java are handled "by reference"
y Comparison is by reference
Following is true if b1, b2 point to the same object
if (b1 == b2) { } if (b1.equals(b2)) { } // member by member comparison

y Assignment copies the reference


b1 = b2; b1.clone(b2); // Convention for copying an object

y Parameters passing is always by value


y The value is always copied into the method y For objects, the reference is copied (passed by value)
The object itself is not copied It is possible to change the original object via the reference
22

Parameter Passing Example


class ParameterPassingExample { static public void main (String[] args) { int ai = 99; StringBuffer as1 = new StringBuffer("Hello"); StringBuffer as2 = new StringBuffer("World"); System.out.println ("Before Call: " + show(ai, as1, as2)); set(ai,as1,as2); System.out.println ("After Call: " + show(ai, as1, as2)); } static void set (int fi, StringBuffer fs1, StringBuffer fs2) { System.out.println ("Before Change: " + show(fi, fs1, fs2)); fi=1; fs1.append(", World"); fs2 = new StringBuffer("Hello, World"); System.out.println ("After Change: " + show(fi, fs1, fs2)); } static String show (int i, StringBuffer s1, StringBuffer s2) { return "i=" + i + "s1='" + s1 + "'; s2='" + s2 + "'"; } }
Before Call : Before Change: After Change : After Call : i= i= i= i= 99 99 1 99 s1='Hello'; s2='World' s1='Hello'; s2='World' s1='Hello, World'; s2='Hello, World' s1='Hello, World'; s2='World'

23

Constants
y Constants
y Value of variable is not allowed to change after initialization
Example
final double PI = 3.14159;

Initialization can be done after declaration


final boolean debug_mode; if (x<20) debug_mode = true; // Legal else debug_mode = false; // Legal debug_mode = false; // Error is caught at compile time

Value of variable cannot change; value of object can change


final Button p = new Button("OK"); p = new Button ("OK"); // Illegal. P cannot point to // a different object p.setLabel ("Cancel"); // Legal.

24

Input/Output
y java.io.OutputStream - A byte output stream
System.out (C:stdout; C++:cout) System.err (C:stderr; C++:cerr)

y Convenience methods: print, println


send characters to output streams

y java.io.InputStream - A byte input stream


System.in (C:stdin; C++:cin)

y InputStreamReader
Reads bytes and converts them to Unicode characters

y BufferedReader
Buffers input, improves efficiency Convenience method: readLine()
InputStreamReader isr = new InputStreamReader(System.in); BufferedReader stdin = new BufferedReader (isr); String s1 = stdin.readLine();
25

Echo.java
A version of Echo that reads in data from System.in
import java.io.*; class Echo { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); String message; System.out.println ("Enter a line of text:"); message = stdin.readLine(); System.out.println ("Entered: \"" + message + "\""); } // method main } // class Echo

java.lang.Integer.parseInt converts a string to an integer


int message_as_int = Integer.parseInt(message);

java.io.StreamTokenizer handles more advanced parsing

26

Programming in Java
Classes, Inheritance, Interfaces

27

Array Declaration
y Array Declaration
y Example
int[] scores = new int[10];

y y y y

Variable type is "int[]" Elements range from scores[0] scores[9] Automatic bounds checking Each array has a public constant, length
scores.length - this evaluates to 10

y Alternate declarations
float[] prices; float prices[];

28

Arrays
y Initializer lists can be specified
int[] units = { 147, 323, 89 };

No new operator used No size specified

y Elements of an array can be object references


Strings[] words = new String[25];

This reserves space to store 25 references to String objects String objects are not automatically created

y Arrays can be passed to methods


The reference is passed (true for all objects)

y Size of array is not part of type


A variable of type String[] can store ANY array of Strings, of any size

29

Multi-Dimensional Arrays
y Multi-dimensional arrays
y A two dimensional array is an array of arrays
byte my_array[][] = new byte[2][5]

Memory is NOT necessarily contiguous


0,0 0,1 0,2 0,3 0,4 1,0 1,1 1,2 1,3 1,4

[C] [Java]

79 87 94 82 67 98 87 81 74 91

79 87 94 82 67
0,0 0,1 0,2 0,3 0,4

98 87 81 74 91
1,0 1,1 1,2 1,3 1,4
30

Multi-Dimensional Arrays
y Each row (inner array) is independent of others
Can reassign part of the array
my_array[1] = new byte[22];

Each row can have a different size than other rows


int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} };

Can have partial declarations


byte my_partial_array[][] = new byte[3][]; String lots_of_strings[][][][] = new String[5][3][][];

All missing dimensions MUST be at the end


String more_strings[][][] = new String[5][][3]; // Not valid

31

Vectors
y Arrays
y Once memory is allocated, the array size cannot change
String[] my_array = new String[20]; my_array = new String[10]; // OK; loses pointer to old array my_array.length = 30; // Not allowed

y java.util.Vector
y Another way to represent list of values
Size of a Vector can change dynamically
Vector courses = new Vector(20); // Compare to array decl. courses.addElement ("Lisp"); courses.addElement ("Perl"); // courses.addElement (220); // Not allowed courses.addElement (new Integer(220)); // OK with wrapper courses.size () // Returns 3 courses.capacity() // returns 20

32

Arrays vs. Vectors


y Differences between Arrays and Vectors
y Vectors are dynamic (size can change) y Vector is more like a typical java class
No special syntax or operators (for ex. No [ ] operator for accessing)

y Can only have Vectors of Objects


Any object, but no primitive types No strong type checking (No mechanisms for templates in Java) Compiler cannot help prevent "Line objects" from getting into a vector that should only contain "Point objects"

y Vectors are implemented using an array of Object


protected Object[] elementData;

Implications of insert, remove, resize operations

33

Vector
y Constructors
Vector(int initialCapacity) Vector(int initialCapacity, int capacityIncrement) Vector() // Default initial capacity is 10

y Size/Capacity methods
public public public public public final final final final final

int capacity(); synchronized void ensureCapacity(int minCap); synchronized trimToSize(); int size(); synchronized void setSize(int newSize);

y Methods overridden from Object

public synchronized Object clone(); public final synchronized void toString();

34

Vector
y Adding/Removing Elements
public final void addElement(Object arg); - Increases size; may increase capacity public final boolean removeElement (Object arg); - Reduces size; returns false if unsuccessful

y Random Access

public final Object elementAt (int index) - Analogous to an array [ ] operator public final void insertElementAt (int index) public final void removeElementAt (int index) public final void setElementAt (Object arg, int index)

y Finding objects

public final int indexOf (Object arg) public final int indexOf (Object arg, int index) - Return -1 if object is not found

35

StringTokenizer, StringBuffer
y StringTokenizer class y StringBuffer class
y Like String, but allows changes
append
StringBuffer text1 = new StringBuffer ("Hello"); text1.append (" World");

Other useful methods


insert (int index, char c); charAt (int index); setCharAt (int index, char c); reverse(); length();

36

StringBuffer Example
y StringBuffer.append is similar to String.concat
public class Concat { public static void main (String[] args) { String s = new String ("Hello "); String s2 = s.concat ("World"); StringBuffer sb = new StringBuffer("Hello "); StringBuffer sb2 = sb.append ("World"); System.out.println System.out.println System.out.println System.out.println } } // class Concat ("s: ("sb: ("s2: ("sb2: " " " " + + + + s); sb); s2); sb2);

y What is the difference?


37

Class Example
y Declaration
import java.lang.Math; public class Circle { public int x, y, r; // (x,y) of Center; radius public double circumference () { return 2 * Math.PI * r; } public double area () { return Math.PI * r * r; } }

y Use

Circle c; c = new Circle(); c.r = 2; double a = c.area();

38

Constructors
y Constructors
Perform initialization of objects Declaration
public class Circle { private int x, y, r; public Circle (int ar) { this.x=0; y=0; r=ar; } // Note the optional use of "this" above }

Use
Circle c = new Circle (2); double a = c.area();

Can have more than one constructor


public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }

Can overload the default constructor


public Circle () { x=0; y=0; r=1; }

What if a class does not define ANY constructors? What if a class defines constructors, but not one with NO arguments?
39

Constructors
y One constructor can call another (unlike C++)
y Uses "this"
public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; } public Circle (int ar) { this(0, 0, ar); }

y Call to an alternate constructor MUST appear first


y Before any other statements y Before variable declarations

40

Class Variables
y Class variables
import java.lang.Math; public class Circle { static int numCircle = 0; private int x=0, y=0, r=1; // Notice the initializers public Circle() { num_circles++; } public Circle (int ar) { this(); r=ar; } public double circumference () { return 2 * Math.PI * r; } public double area () { return Math.PI * r * r; } }

y Referencing Class variables


From within the class: this.numCircle (or just numCircle)
public Circle() { this.numCircle++; }

From outside the class: Circle.num_circle


Circle c = new Circle(); System.out.println ("# Circles= " + c.numCircle); System.out.println ("# Circles= " + Circle.numCircle);
41

Class Methods
y Class methods
import java.lang.Math; public class Circle { private int x,y,r; int getX () { return this.x; } static int numCircle = 0; public static int getNumCircle() { return this.numCircle;} }

y Calling class methods


From within the class
this.getNumCircle();

From outside the class


Circle c = new Circle(); int n1 = c.getNumCircle(); int n2 = Circle.getNumCircle();

42

(Lack of) Globals


y Java does not allow global variables
y Class variables can substitute for global variables
Advantage: no possibility of a collision in variable names Example declaration in java.lang.Math:
public final static double PI;

Example usage:
public double circumference () { return 2 * Math.PI * r; } System.out.println ("Hello");

y Java does not allow global functions or methods


y Class methods can substitute for global functions
Example declaration in java.lang.Integer:
public static int parseInt(String str);

Example usage:
int i = Integer.parseInt ("73"); double sqrt_i = Math.sqrt(i);
43

Inheritance
y Need a class with ability to draw Circles
y Approach 1 (Not ideal)
public class GraphicCircle { // Keep an instance var. to keep circle stuff public Circle c; // Delegate functionality to c public double area() { return c.area(); } public double circumference () {return c.circumference();} // Add in GraphicCircle specific stuff public Color outline, fill; public void draw (Graphics page) { } }

44

Inheritance
y Approach 2: Inheritance
A "GraphicCircle" isa (more specific version of) "Circle"
public class GraphicCircle extends Circle { // Only need the 'additional' things Color outline, fill; public void draw (Graphics page) { } }

y Terms and Concepts


Superclass, base class, parent class Subclass, derived class, child class isa, Class Hierarchy Inheritance of instance variables and methods Circle GraphicCircle

Circle

GraphicCircle

45

Inheritance
y GraphicCircle inherits all variables and methods
GraphicCircle gc = new GraphicCircle (); gc.draw(); // Can invoke GraphicCircle methods gc.x = 5; // Can access Circle fields a = gc.area(); // Can invoke Circle methods

y GraphicCircle objects are also Circle objects

Circle c; c = gc; // Assignment is legal a = c.area(); // Code can treat c as any other Circle c.draw(); // Illegal (draw is defined in GraphicCircle) boolean b1, b2; b1 = (c instanceof GraphicCircle); // True b2 = (c instanceof Circle); // True

46

Class Hierarchy
y All classes (except one) have a single superclass
No multiple inheritance Object is the default superclass Object Circle GraphicCircle

y Classes and inheritance relationships form a Tree


Called Inheritance Hierarchy Root of Tree is Object All Java classes are part of this hierarchy Object Number Boolean String Integer Float Byte
47

Constructor Chaining
y A subclass invokes a superclass constructor
y Explicitly - First line is a call to the superclass constructor
class GraphicCircle { public GraphicCircle (int r, Color o, Color f) { super(r); // Must be first line this.outline = o; this.fill = f; }

y Implicitly
If first line of constructor is not a call to a constructor, super() is automatically invoked
- What if supertype doesn't define a constructor with no arguments? - What if first line is a call to another constructor of the form this()?

y Note: Body of supertype constructor executes first (Like C++)!


48

Overriding Methods
y Subclass can redefine method of superclass
class Circle { public void reset () { x=0; y=0; r=1; } } class GraphicCircle { public void reset () { x=0; y=0; r=1; fill = Color.getColor ("black"); } }

y Subclass method can call superclass method


class GraphicCircle { public void reset () { super.reset(); fill = Color.getColor("black"); } }

49

Polymorphism; Final Modifier


y Actual method to call is determined at runtime
y Depends on actual objects type (not variable type)
Circle[] c[2]; c[0] = new Circle(); c[1] = new GraphicsCircle(); for (int i=0; i<2; i++) c[i].reset();

y C++ requires virtual keyword to implement polymorphism


C++ default (without keyword): resolution is done at compile time Java: methods are virtual by default polymorphism Can use final keyword modifier to enable compile time resolution
class Circle { public final void reset () { x=0; y=0; r=1; } } class GraphicCircle { public void reset () { } // No longer valid! }
50

Finalize Methods
y Finalize: Similar to C++ destructor
y A place to clean up an object before memory is deallocated
Invoked before garbage collection

y Typically used for closing files, releasing resources, etc.


public class FileOutputStream extends OutputStream { // From java.io.FileOutputStream protected void finalize() throws IOException { if (fd != null) close(); // Closes file descriptor } }

y Not very common in Java (compared to C++)


Most cleanup is done automatically by the garbage collector

y Not guaranteed to be called


Program may exit without ever calling the finalizer Operating system must free any outstanding resources after exit
51

Finalize Methods
y Java chains constructor methods (like C++ y Java does NOT chain finalize methods
If you define a finalizer, you should invoke the supers finalizer explicitly
class GraphicCircle extends Circle { protected void finalize () { local cleanup super.finalize(); more local cleanup } }

52

Visibility Modifiers
y Public, Private, Protected, Package
public class Circle { // With mixed visibility public int x; // Public visibility protected int y; // Protected visibility int r; // Package visibility (default) private int numCircle; // Private visibility int area() { } }

y Package visibility is default


classes in same package are friend-ly to each other
Accessible to Same Class Class in same package Subclass in different package Non-subclass, different package Public Y Y Y Y Protected Package Private Y Y Y Y Y Y

53

Visibility Modifier Guidelines


y Public
Use this for methods, constants that are part of the public API Most variables should not be public

y Protected
For members that might be useful to subclasses (e.g. Circles x,y,r) But not for public use

y Package
For things that cooperating classes need access to

y Private
Fields and methods that should be hidden from everyone else

54

Circle Class
public class Circle { protected int x=0, y=0, r=1; private static int numCircle=0; // No one has access /* Constructors */ public Circle () { numCircle++; } public Circle (int ar) { this(); r=ar; } // Public way to public final int public final int public final int public final int get to variables (final for optimization) getNumCircle() { return numCircle; } getX() { return x; } getY() { return y; } getR() { return r; }

// Methods to set variables public void moveTo (int newx, newy) { x=newx; y=newy; } public void move (int dx, int dy) { x+=dx; x+=dy; } public void setRadius (double newr) { r = newr; } }

55

Final Classes; Abstract Classes


y Final (no analogy in C++)
y Method
Cannot be redefined by subclass

y Class
Cannot be subclassed
public final class System extends Object { } public class MyClass extends System { } // Not valid

y Abstract
y Method (analogous to a pure virtual function in C++)
Must be redefined by subclass

y Class
Cannot be instantiated If a class has an abstract method, it must be declared an abstract class
56

Abstract Class Example


public abstract class Shape { public abstract double area(); // Note: no definition public abstract double circumference(); } public class Circle extends Shape { protected int x, y, r; public Circle(int ar) { r=ar; } public double area() { return Math.PI * r * r; } public double circumference() { return 2 * Math.PI * r; } } public class Rectangle extends Shape { protected int x, y, w, h; public Rectangle (int aw, int ah) { w=aw; h=ah; } public double area() { return w * h; } public double circumference() { return 2 * (w + h); } }

57

Abstract Class Example


y Example usage
public static void main () { Shape[] shapes = new Shape[3]; shapes[0] = new Circle(2); shapes[1] = new Rectangle (3,4); shapes[2] = new Rectangle (2,3); double total_area = 0; for (int i=0; i<shapes.length; i++) total_area += shapes[i].area(); }

y Subclasses of Shape can be assigned to an array of Shape y Area() method can be invoked on any kind of Shape
Declared as an abstract method in Shape Not valid if area() method was not defined in Shape

58

Inheritance
y Example Hierarchy
Shape - abstract area(), circumference() Circle - area(), circumference() GraphicCircle - draw() Rectangle - area(), circumference() GraphicRectangle - draw()

Want to have a Drawable class, with an abstract draw()

y In C++
Multiple Inheritance Drawable Circle

Shape

Rectangle

GraphicCircle

GraphicRectangle
59

Interface
y Java
y No multiple inheritance y Java's solution: interface
public interface Drawable { public void setColor (Color c); public void setPosition (int x, int y); public void draw (Graphics dw); }

y Interface
y Looks like an abstract class; simulates some Multi-Inheritance
But uses keyword interface instead of abstract and class All methods are abstract by default All instance variables must be constants (static and final)

y Other classes can implement an interface


60

Interface
public class GraphicRectangle extends Rectangle implements Drawable { private Color c; public GraphicRectangle (int w, int h) { super(w,h); } // Implement each method in Drawable public void setColor (Color ac) { c = ac; } public void setPosition (int ax, int ay) { x=ax; y=ay; } public void draw(Graphics dw) { ... } }

61

Using Interfaces
Shape[] shapes = new Shape[3]; Drawable[] drawables = new Drawable[3]; GraphicCircle dc = new GraphicCircle(1); GraphicRectangle dr = new GraphicRectangle (3,4); GraphicCircle dc2 = new GraphicCircle(3); // Add them shapes[0] = shapes[1] = shapes[2] = to arrays dc; drawables[0] = dc; dr; drawables[1] = dr; dc2; drawables[2] = dc2;

double total_area = 0; for (int i=0; i<shapes.length; i++) { total_area += shapes[i].area(); drawables[i].setPosition(i*10, i*10); drawables[i].draw(gc); // Assume gc is defined somewhere }

62

Multiple Interfaces
y Each user defined class
y Extends exactly one other class y Implements 0, 1, or more interface
public class GraphicRectangle extends Rectangle implements Drawable, java.lang.Cloneable, java.lang.Serializable { ... }

y Interface
y Provides a way to simulate multiple inheritance y Every class that implements an interface MUST define all methods of that interface
63

Interface Hierarchy
y Interfaces can be subtypes of other interfaces
y Results in an interface hierarchy
Directed, Acyclic Graph (not a tree, like the class hierarchy)
public interface Transformable extends Scalable, Rotateable, Reflectable { ... } public interface GraphicObject extends Drawable, Transformable { ... } public class Shape implements GraphicObject { ... }

64

Case Study on Inheritance


y Case Study
Solution: Lewis: ../chap08/applications/Accounts2.java

y Bank_Account
Generic account with ability to make deposits and withdrawals

y Savings_Account
A kind of Bank_Account Collects interest Bank_Account

Savings_Account A kind of Savings_Account Checking_Account Collects more interest Has penalties for withdrawal Bonus_Saver_Account y Checking_Account A kind of Bank_Account Has overdraft protection
65

y Bonus_Saver_Account

Define Class Hierarchy


public ... } public ... } public ... } public ... } class Bank_Account { class Savings_Account extends Bank_Account {

class Bonus_Saver_Account extends Savings_Account {

class Checking_Account extends Bank_Account {

public class Accounts2 { public static void main (String[] args) { ... Create objects and test out class hierarchy ... } }

66

Define Methods
public class Bank_Account { public Bank_Account(int account_num,double init_bal) {...} public void deposit (double amount) { ... } public void withdrawal (double amount) { ... } } public class Savings_Account extends Bank_Account { public void add_interest () { ... } } public class Bonus_Saver_Account extends Savings_Account { public void withdrawal (double amount) { ... penalty ... } public void add_interest () { ... give bonus rate ... } } public class Checking_Account extends Bank_Account { public void withdrawal (double amount) { ... check for overdraft ... } }

67

Define Methods (Details)


public class Bank_Account { protected int account; protected double balance; public Bank_Account(int account_num,double init_bal) {...} Bank_Account aBA = new Bank_Account(4321, 100.00); public void deposit (double amount) { ... } aBA.deposit (50.00); public void withdrawal (double amount) { ... } aBA.withdraw (20.00); }

68

Define Methods (Details, cont.)


public class Savings_Account extends Bank_Account { protected double rate; public Savings_Account (int account_num, double initial_balance, double interest_rate) { ... } Savings_Account aSA = new Savings_Account (1234, 100.00, 0.05); public void add_interest () { ... } aSA.add_interest(); } public class Bonus_Saver_Account extends Savings_Account { public Bonus_Saver_Account (int account_num, double initial_balance, double interest_rate) { ... } Bonus_Saver_Account aBSA = new Bonus_Saver_Account (1234, 100.00, 0.05); public void withdrawal (double amount) { ... penalty ... } aBSA.withdraw ( 20.00 ); public void add_interest () { ... give bonus rate ... } aBSA.add_interest (); }
69

Define Methods (Details, cont.)


public class Checking_Account extends Bank_Account { private Savings_Account overdraft; public Checking_Account (int account_number, double initial_balance, Savings_Account protection) {...} Checking_Account aCA = new Checking_Account (87323, 75.00, aBSA); public void withdrawal (double amount) { if (checking account has enough funds) take funds out of checking account else if overdraft account has enough funds take funds out of overdraft account else print error "Insufficient funds" } aCA.withdraw (20.00); }

70

Bank_Account
class Bank_Account { protected int account; protected double balance; public Bank_Account (int account_num, double init_bal) { account = account_num; balance = initial_balance; } // constructor Bank_Account public void deposit (double amount) { balance += amount; System.out.println("Deposit into account " + account); System.out.println("Amount: " + amount); System.out.println("New balance: " + balance); System.out.println(); } // method deposit // ... rest is on next slide

71

Bank_Account (cont.)
public boolean withdrawal (double amount) { boolean result = false; System.out.println("Withdrawal from account " + account); System.out.println ("Amount: " + amount); if (amount > balance) System.out.println ("Insufficient funds."); else { balance -= amount; System.out.println ("New balance: " + balance); result = true; } System.out.println(); return result; } // method withdrawal } // class Bank_Account

72

Savings_Account
class Savings_Account extends Bank_Account { protected double rate; public Savings_Account (int account_num, double initial_balance, double interest_rate) { super (account_num, initial_balance); rate = interest_rate; } // constructor Savings_Account public void add_interest () { balance += balance * rate; System.out.println ("Interest added to account: " + account); System.out.println ("New balance: " + balance); System.out.println(); } // method add_interest // class Savings_Account

73

Bonus_Saver_Account
class Bonus_Saver_Account extends Savings_Account { private final int PENALTY = 25; private final double BONUS_RATE = 0.03; public Bonus_Saver_Account (int account_num, double initial_balance, double interest_rate) { super (account_num, initial_balance, interest_rate); } // constructor Super_Saver_Account public boolean withdrawal (double amount) { System.out.println ("Penalty incurred: " + PENALTY); return super.withdrawal (amount+PENALTY); } // method withdrawal

74

Bonus_Saver_Account (cont.)
public void add_interest () { balance += balance * (rate + BONUS_RATE); System.out.println ("Interest added to account: " + account); System.out.println ("New balance: " + balance); System.out.println(); } // method add_interest } // class Bonus_Saver_Account

75

Checking_Account
class Checking_Account extends Bank_Account { private Savings_Account overdraft; public Checking_Account (int account_number, double initial_balance, Savings_Account protection) { super (account_number, initial_balance); overdraft = protection; } // constructor Checking_Account // ... continued on next slide

76

Checking_Account (cont.)
//... public boolean withdrawal (double amount) { boolean result = false; if ( ! super.withdrawal (amount) ) { System.out.println ("Using overdraft..."); if ( ! overdraft.withdrawal (amount-balance) ) System.out.println("Overdraft funds insufficient."); else { balance = 0; System.out.println ("New balance on account " + account + ": " + balance); result = true; } } System.out.println (); return result; } // method withdrawal } // class Checking_Account

77

Main
class Accounts2 { public static void main (String[] args) { Savings_Account savings = new Savings_Account (4321, 5028.45, 0.02); Bonus_Saver_Account big_savings = new Bonus_Saver_Account (6543, 1475.85, 0.02); Checking_Account checking = new Checking_Account (9876, 269.93, savings); savings.deposit (148.04); Deposit into account 4321 Amount: 148.04 New balance: 5176.49 big_savings.deposit (41.52); Deposit into account 6543 Amount: 41.52 New balance: 1517.37

78

Main (cont.)
savings.withdrawal (725.55); Withdrawl from account 4321 Amount: 725.55 New balance: 4450.94 big_savings.withdrawal (120.38); Penalty incurred: 25 Withdrawl from account 6543 Amount: 145.38 New balance: 1371.9899999999998 checking.withdrawal (320.18); Withdrawl from account 9876 Amount: 320.18 Insufficient funds. Using overdraft... Withdrawl from account 4321 Amount: 50.25 New balance: 4400.69 New balance on account 9876: 0.0 } // method main } // class Accounts2

79

Programming in Java
Collections

80

Contents
y y y y y y y y y y Collections, Iteration The Collection Interface Set and SortedSet List Queue Map and SortedMap Enum Collections Wrapped Collections and the Collections Class Writing Iterator Implementations The Legacy Collection Types

81

Collections
y Collections are holders that let you store and organize objects in useful ways for efficient access. y In the package java.util, there are interfaces and classes that provide a generic collection framework. y The Collections interfaces: Collection<E>, Set<E>, SortedSet<E>, List<E>, Queue<E>, Map<K,V>, SortedMap<K,V>, Iterator<E>, ListIterator<E>, Iterable<E> y Some useful implementations of the interfaces: HashSet<E>, TreeSet<E>, ArrayList<E>, LinkedList<E>, HashMap<K,V>, TreeMap<K,V>, WeakHashMap<K,V> y Exception Convetions:
y y y y y

UnsupportedOperationException ClassCastException IllegalArgumentException NoSuchElementException NullPointerException

82

Type Trees for Collections


Iterable<E> Iterator<E> Collection<E> ListIerator<E>

Set<E>

Queue<E> EnumSet<E> HashSet<E>

List<E> ArrayList<E> LinkedList<E>

SortedSet<E>

PriorityQueue<E>

TreeSet<E> LinkedHashSet<E> Map<K,V> EnumMap<K,V> SortedMap<K,V> WeakHashMap<K,V> HashMap<E> TreeMap<K,V>

LinkedHashMap<K,V> 83

The Collections Framework


y y

The Java collection framework is a set of generic types that are used to create collection classes that support various ways to store and manage objects of any kind in memory. A generic type for collection of objects: To get static checking by the compiler for whatever types of objects to want to manage.

Generic Types
Generic Class/Interface Type The Iterator<T> i terf e ty e Description Decl res ethods for iter ti through elements of collection, one t time.

The Vector<T> ty e

Supports n rr y-li e structure for storing ny type of object. The number of objects to be stored increases automatically as necessary. Supports the storage of any type of object in a pushdown stack.

The Stack<T> type

The LinkedList<T> type

Supports the storage of any type of object in a doubly-linked list, which is a list that you can iterate though forwards or backwards. Supports the storage of an object of type V in a hash table, sometimes called a map. The object is stored using an associated key object of type K. To retrieve an object you just supply its associated key.

The HashMap<K,V> type

84

Collections of Objects
 Three Main Types of Collections  Sets  Sequences  Maps  Sets
 The simple kinds of collection  The objects are not ordered in any particular way.  The objects are simply added to the set without any control over where they go.

85

Collections of Objects
 Sequences
 The objects are stored in a linear fashion, not necessarily in any particul ar order, but in an arbitrary fixed sequence with a beginning and an end.  Collections generally have the capability to expand to accommodate as many elements as necessary.  The various types of sequence collections
Array or Vector LinkedList Stack Queue

86

Collections of Objects
 Maps
 Each entry in the collection involves a pair of objects.  A map is also referred to sometimes as a dictionary.  Each object that is stored in a map has an associated key object, and the object and its key are stored together as a name-value pair.

87

Iterators and ListIterators


y

Iterator<E> interface y T next() y boolean hasNext() y void remove() ListIterator<E> interface y extends Iterator y T next() y boolean hasNext() y int nextIndex() y T previous() y boolean hasPrevious() y int previousIndex() y void remove() y void add(T obj) y void set(T obj)

public void removeLongStrings (Collection<? Extends String> coll, int maxLen) { Iterator<? Extends String> it = coll.iterator(); while (it.hasNext()) { String str = it.next(); if (Str.length() > maxLen) it.remove(); } } ListIterator<String> it = list.listIterator(list.size()); while (it.hasPrevious()) { String obj = it.previous(); System.out.println(obj); // use obj . }

88

Comparable and Comparator


y The interface java.lang.Comparable<T> can be implemented by any class whose objects can be sorted. y public int compareTo (T other): return a value that is less than, equal to, or greater than zero as this object is less than, equal to, or greater than the other object. y If a given class does not implement Comparable or if its natural ordering is wrong for some purpose, java.util.Comparator object can be used y public int compare(T o1, T o2) y boolean equals(Object obj)

89

The Collection Interface


y

The ollection Interface


y The basis of much of the collection system is the Collection interface.

String[] strings = new String[collection.size()]; strings = collection.toArray(strings); String[] strings = collection.toArray(new String[0]);

y Methods:
y public int size() y public boolean isEmpty() y public boolean contains(Object elem) y public Iterator<E> iterator() y public Object[] toArray() y public <T> T[] toArray(T[] dest) y public boolean add(E elem) y public boolean remove(Object elem)

y public boolean containsAll(Collection<?> coll) y public boolean addAll(Collection<? extends E> coll) y public boolean removeAll(Collection<?> coll) y public boolean retainAll(Collection<?> coll) y public void clear()

90

Collection Classes
y

Classes in Sets:
y y y y

Class in Queues:
y FIFO ordering y PriorityQueue<T>

HashSet<T> LinkedHashSet<T> TreeSet<T> EnumSet<T extends Enum<T>>

Classes in Maps:
y Does not extend Collection because it has a contract that is different in important ways: do not add an element to a Map(add a key/value pair), and a Map allows looking up. y Hashtable<K,V> y HashMap<K,V> y LinkedHashMap<K,V> y WeakHashMap<K,V> y IdentityHashMap<K,V> y TreeMap<K,V> : keeping its keys sorted in the same way as TreeSet

Classes in Lists:
y To define a collection whose elements have a defined order-each element exists in a praticular poistion the collection. y Vector<T> y Stack<T> y LinkedList<T> y ArrayList<T>

91

Writing Iterator Implementations


ShortStrings.java

import java.util.*; public class ShortStrings implements Iterator<String> { private Iterator<String> strings ; // source for strings private String nextShort; // null if next not known private final int maxLen; // only return strings <= public ShortStrings(Iterator<String> strings, int maxLen) { this.strings = strings; this.maxLen = maxLen; nextShort = null; } public boolean hasNext() { if (nextShort != null) // found it already return true; while (strings.hasNext()) { nextShort = strings.next(); if (nextShort.length() <= maxLen) return true; } nextShort = null; // did not find one return false; }

public String next() { if (nextShort == null && !hasNext()) throw new NoSuchElementException(); String n = nextShort; // remember nextShort nextShort = null; return n; } public void remove() { throw new UnsupportedOperationException(); } } ShortStringsTest.java import java.util.*; public class ShortStringsTest { public static void main(String[] args) { LinkedList<String> myList = new LinkedList<String>(); myList.add("First String"); myList.add("Second Second String"); myList.add("Third Third Third String"); myList.add("Fourth Fourth Fourth Fourth String"); myList.add("Fifth Fifth Fifth Fifth Fifth String"); ShortStrings myShort = new ShortStrings(myList.iterator(), 25); // for (String val : myShort) // Why not able ? while(myShort.hasNext()) { System.out.println("Short String = " + myShort.next());} }} }

Result:
Short String = First String Short String = Second Second String Short String = Third Third Third String

92

Binary Tree Example Using Collection Framework


LinkedList.java public class LinkedList<T> implements Iterable<T> { . public Iterator<T> iterator() { return new ListIterator(); } private class ListIterator implements Iterator<T> { . } . } // end of LinkedList

BinaryTree.java public class BinaryTree<T extends Comparable<T>> { some_add_method_for tree(T value, Node node) { // call node.obj.compareTo(value); } class Node { T obj; } Read the codes of LinkedList.java, BinaryTree.java, and TryBinaryTree.java } carefully. nd compare this to the contents of the slide #13.
And Run TryBinaryTree.
93

The Legacy Collection Types


y Enumeration
y Analogous to Iterator.

y Vector
y Analogous to ArrayList, maintains an ordered list of elements that are stored in an underlying array.

y Stack
y Analogous of Vector that adds methods to push and pop elements.

y Dictionary
y Analogous to the Map interface, although Diectionary is an abstract class, not an interface.

y Hashtable
y Analogous HashMap.

y Properties
y A subclass of Hashtable. Maintains a map of key/value pairs where the keys and values are strings. If a key is not found in a properties object a default properties object can be searched.

94

Vector (Before 1.5)


class VectorDemo { public static void main(String args[]) { // Create a vector and its elements Vector vector = new Vector(); vector.addElement(new Integer(5)); vector.addElement(new Float(-14.14f)); vector.addElement(new String("Hello")); vector.addElement(new Long(120000000)); vector.addElement(new Double(-23.45e-11)); // Display the vector elements System.out.println(vector); // Insert an element into the vector String s = new String("String to be inserted"); vector.insertElementAt(s, 1); System.out.println(vector); // Remove an element from the vector vector.removeElementAt(3); System.out.println(vector); } } 95 Result :
[5, -14.14, Hello, 120000000, -2.345E-10] [5, String to be inserted, -14.14, Hello, 120000000, -2.345E-10] [5, String to be inserted, -14.14, 120000000, 2.345E-10]

Integer

Float

String

Long

Vector

Vector (Using Generic Type)


import java.util.Vector; import java.util.ListIterator; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; class Person { // Constructor public Person(String firstName, String surname) { this.firstName = firstName; this.surname = surname; } public String toString() { return firstName + " " + surname; } private String firstName; private String surname; } // First name of person // Second name of person // Show who is in the cast using an iterator ListIterator<Person> thisLot = filmCast.listIterator(); while(thisLot.hasNext()) { // Output all elements System.out.println( thisLot.next()); } } // Read a person from the keyboard static Person readPerson() { // Read in the first name and remove blanks front and back String firstName = null; String surname = null; System.out.println( "\nEnter first name or ! to end:"); try { firstName = keyboard.readLine().trim(); // Read and trim a string if(firstName.charAt(0) == '!') { return null; } // Check for ! entered // If so, we are done...

public class TryVector { public static void main(String[] args) { Person aPerson = null; // A person object Vector<Person> filmCast = new Vector<Person>(); // Populate the film cast for( ; ; ) { // Indefinite loop aPerson = readPerson(); // Read in a film star if(aPerson == null) { // If null obtained... break; // We are done... } filmCast.add(aPerson); // Otherwise, add to the cast } } int count = filmCast.size(); System.out.println("You added " + count + (count == 1 ? " person": " people") + " to the cast.\n"); System.out.println("The vector currently has room for " + (filmCast.capacity() - count) + " more people.\n");

// Read in the surname, also trimming blanks System.out.println("Enter surname:"); surname = keyboard.readLine().trim(); // Read and trim a string } catch(IOException e) { System.err.println("Error reading a name."); e.printStackTrace(); System.exit(1); } return new Person(firstName,surname); }

static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

Try TryVector.java What are differences to those of the V1.4? 96

Hashtable (Before 1.5)


class HashtableDemo { public static void main(String args[]) { Hashtable hashtable = new Hashtable(); hashtable.put("apple", "red"); hashtable.put("strawberry", "red"); hashtable.put("lime", "green"); hashtable.put("banana", "yellow"); hashtable.put("orange", "orange"); Enumeration e = hashtable.keys(); while(e.hasMoreElements()) { Object k = e.nextElement(); Object v = hashtable.get(k); System.out.println("key = " + k + "; value = " + v); } System.out.print("\nThe color of an apple is: "); Object v = hashtable.get("apple"); System.out.println(v); } }
97 Key Value

The Hashtable<k,V> class inherits from the Dictionary class, and implement the Map interface. All methods of it are synchronized, unlike HashMap.

Result :
Result #2 key = lime; value = green key = strawberry; value = red The color of an apple is: red

Here, you will meet warning message of unchecked type. How can we solve this?

Hashtable<K,V> (1.5)
import java.util.*; class HashtableDemoGen { public static void main(String args[]) { Hashtable<String,String> hashtable = new Hashtable<String,String>(); hashtable.put("apple", "red"); hashtable.put("strawberry", "red"); hashtable.put("lime", "green"); hashtable.put("banana", "yellow"); hashtable.put("orange", "orange"); for (Enumeration<String> e = hashtable.keys() ; e.hasMoreElements() ;) { String k = e.nextElement(); String v = hashtable.get(k); System.out.println("key = " + k + "; value = " + v); } System.out.print("\nThe color of an apple is: "); String v = hashtable.get("apple"); System.out.println(v); } } 98 Parameterized Type

The Hashtable<k,V> class inherits from the Dictionary class, and implement the Map interface. All methods of it are synchronized, unlike HashMap.

Miscellaneous Utilities
y Formatter A class for producing formatted text. y BitSet A dynamically sized bit vector y Observer/Observable An interface/class pair that enables an object to be observable by having one or more Observer objects that are notified when something interesting happens in the Observable object. y Random A class to generate sequences of pseudorandom numbers. y Scanner A class for scanning text and parsing it into values of primitive types or strings, based on regular expression patterns. y StringTokenizer A class that splits a string into tokens based on delimiters(by default, whitespace) y Timer/TimerTask A way to schedule tasks to be run in the future. y UUID A class that represents a universally unique identifier(UUID) y Math A class performing basic mathematical operations, such as trigonometric functions, exponentiation, lograithms, and so on. y StricMath Defines the same methods as Math but guarantees the sue of specific algorithms that ensure the same results on every virtual machine.
99

Programming in Java
Threads

100

A single threaded program


class ABC { .
public void main(..) { .. }
begin

body end

101

A Multithreaded Program

Main Thread

start start start

Thread A

Thread B

Thread C

Threads may switch or exchange data/results


102

Single and Multithreaded Processes


threads are light-weight processes within a process
Single-threaded Process Threads of Execution Multiplethreaded Process

Single instruction stream

Common Address Space

Multiple instruction stream

103

What are Threads?


y A piece of code that run in concurrent with other threads. y Each thread is a statically ordered sequence of instructions. y Threads are being extensively used express concurrency on both single and multiprocessors machines. y Programming a task having multiple threads of control Multithreading or Multithreaded Programming.

104

Java Threads
y y y y Java has built in thread support for Multithreading Synchronization Thread Scheduling Inter-Thread Communication:
y y y y currentThread yield sleep resume start run stop setPriority getPriority suspend

y Java Garbage Collector is a low-priority thread.


105

Threading Mechanisms...
y Create a class that extends the Thread class y Create a class that implements the Runnable interface

106

1st method: Extending Thread class


y Threads are implemented as objects that contains a method called run()
class MyThread extends Thread { public void run() { // thread body of execution } }

y Create a thread: MyThread thr1 = new MyThread(); y Start Execution of threads: thr1.start(); y Create and Execute: new MyThread().start();

107

An example
class MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) { MyThread t = new MyThread(); // due to extending the Thread class (above) // I can call start(), and this will call // run(). start() is a method in class Thread. t.start(); } // end main() } // end class ThreadEx1

108

2nd method: Threads by implementing Runnable interface


class MyThread implements Runnable { ..... public void run() { // thread body of execution } } y Creating Object: MyThread myObject = new MyThread(); y Creating Thread Object: Thread thr1 = new Thread( myObject ); y Start Execution: thr1.start();

109

An example
class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); // due to implementing the Runnable interface // I can call start(), and this will call run(). t.start(); } // end main() } // end class ThreadEx2
110

Life Cycle of Thread


new
start() wait() sleep() suspend() blocked

runnable
stop() notify() slept resume() unblocked

non-runnable

dead

111

Programming in Java
Graphics and Graphical User Interfaces

112

Display of AkmMimic

113

Classes used in Mimic


Object

Component

ai

mponent

La el

tton

i l

Appl

114

Display Components
y Basic code to display components
import java.applet.Applet; import java.awt.*; public class AkmMimic extends Applet { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); this.add (new Button ("OK")); } }

y Applet is a type of Container


y Can add components to containers y Container takes care of "laying out the components" y Default behavior for Applets is "Flow Layout"
Left to right, goes to new rows as necessary
115

Events
y Events can occur on Components
y There are many types of events
Action, Mouse, Key, Focus, Paint, Window

y Listeners watch for events on component


y Listeners in Java are interfaces
(must be implemented by a class)

y Examples:
ActionListener, MouseListener, MouseMotionListener

y Listeners are passed Event objects


y Event objects contain information (e.g. x,y position of mouse) y Examples
ActionEvent, MouseEvent, KeyEvent
116

Events
y Different components can generate different events
y Button, List, TextField, MenuItem
generate ActionEvents

y Any component can generate MouseEvents

y To handle events, have to add listeners y ActionListener is an interface


y Need a class that implements the interface

Button b = new Button ("OK"); ActionListener al = create an action listener b.addActionListener (al);

public abstract interface ActionListener extends EventListener { public abstract void actionPerformed (ActionEvent e); }
117

Listening to the OK button


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); Button b = new Button ("OK"); ActionListener al = new OK_Handler(); b.addActionListener (al); this.add (b); } } class OK_Handler implements ActionListener { public void actionPerformed (ActionEvent e) { System.out.println ("You pressed OK"); } }
118

Applets can also Listen


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet implements ActionListener { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); Button b = new Button ("OK"); b.addActionListener (this); this.add (b); } public void actionPerformed (ActionEvent e) { System.out.println ("You pressed OK"); } }

119

Copying from TextField to Label


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet implements ActionListener { TextField textfield = new TextField(20); Label label = new Label ("No news is good news"); public void init () { this.add (textfield); this.add (label)); Button b = new Button ("OK"); b.addActionListener (this); this.add (b); } public void actionPerformed (ActionEvent e) { label.setText (textfield.getText()); } }
120

Listeners
y Some listeners have multiple methods
public abstract interface MouseListener extends EventListener { public abstract void mouseClicked(MouseEvent e); public abstract void mouseEntered(MouseEvent e); public abstract void mouseExited(MouseEvent e); public abstract void mousePressed(MouseEvent e); public abstract void mouseReleased(MouseEvent e); };

y Classes that implement interfaces


y MUST define code for all methods of the interface
If you only need code in one method, solution isn't clean

121

Handling Mouse Events


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); this.add (new Button("OK")); this.addMouseListener (new MyMouseHandler()); } } class MyMouseHandler implements MouseListener { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { System.out.println ("You pressed a mouse button"); } public void mouseReleased(MouseEvent e) { } }
122

Using Adapters to Listen


y For most listeners, there is a corresponding adapter
class MouseAdapter implements MouseListener { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }

y You can reuse these, and only implement necessary methods


class MyMouseHandler extends MouseAdapter { public void mousePressed (MouseEvent e) { System.out.println ("You pressed a mouse button"); } }

123

Using MouseAdapter
mport java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); this.add (new Button("OK")); this.addMouseListener (new MyMouseHandler()); } } class MyMouseHandler extends MouseAdapter { public void mousePressed(MouseEvent e) { System.out.println ("You pressed a mouse button"); } }

124

Too many classes


y A typical GUI has many buttons, components, menu items, etc. y Need a different class for each listener
y Too many classes y Confuses name space

y Java's solution
y Anonymous, inner classes
Class is embedded in another class Class does not have to have a name provided by developer

125

Anonymous Classes
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); this.add (new Button("OK")); this.addMouseListener (new MouseAdapter () { public void mousePressed(MouseEvent e) { System.out.println ("You pressed a mouse button"); }}); } }

126

Left, Right, or Middle Button?


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class AkmMimic extends Applet { public void init () { this.add (new TextField(20)); this.add (new Label ("No news is good news")); this.add (new Button("OK")); this.addMouseListener (new MouseAdapter () { public void mousePressed(MouseEvent e) { if (e.isMetaDown()) { System.out.println ("Right mouse button pressed"); } else if (e.isAltDown()) { System.out.println ("Middle mouse button pressed"); } else { System.out.println ("Left mouse button pressed"); } }}); } }
127

Вам также может понравиться