JAVA Lectures
Nicolas Saunier
[email protected] 2004-2005
Plan ● ●
●
●
Lecture 1: introduction, the Java syntax. Lecture 2: object-oriented programming, classes, inheritance. Lecture 3: encapsulation and access control, abstract classes and interfaces, inner classes, exceptions. Lecture 4: useful APIs (Application Programming Interface), strings, input/output streams, threads, network, swing, Java 1.5.
Java Lectures
2
Introduction ●
●
What is Java ? –
Java programming language,
–
Java Virtual Machine (JVM),
–
Java Platform.
Compiled Java program: converted into byte codes, –
portable machine language, interpreted by the JVM (specific to the operating system).
Java Lectures
3
“Write once, run everywhere” ●
●
Platform: predefined set of Java classes that exist on every Java installation, available to all Java programs, –
organized in packages,
–
lots of already implemented classes: Network, I/O, graphics...
–
current version: 1.4, 1.5 Release Candidate,
–
SDK ≠ JRE
Secure, efficient...
Java Lectures
4
Particularities ●
No compilation directives, –
●
No explicit manipulation of “pointers”, –
●
no #define, #include. references in Java are entirely opaque.
Memory allocation and garbage collection: no need to deallocate memory.
●
No goto instruction (labeled statements).
●
No structures, no unions types.
Java Lectures
5
First Program ●
file HelloWorld.java –
compiled by javac HelloWorld.java
–
which creates HelloWorld.class
–
executed with java HelloWorld
class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World"); } } Java Lectures
6
Java Syntax ●
Data types,
●
Expressions,
●
Statements,
●
Exceptions,
●
Methods,
●
Classes,
●
Arrays,
●
Packages.
Java Lectures
7
Java Syntax ●
●
Comments: –
single line comment: //
–
multi line comment (not nested): /*...*/
–
documentation comment (javadoc): /**...*/
Identifier: any symbolic name referring to something in a Java program, –
letter|_|$|£|¥ + letter|_|$|£|¥|digits,
–
except reserved words.
Java Lectures
8
Data types ●
Primitive types: –
boolean: boolean,
–
character: char,
–
4 integer types: byte, short, int, long,
–
2 floating-point types: float, double.
●
Type conversions: widening/narrowing (cast).
●
Literal initialization.
Java Lectures
short s = 2; int i = s; short s2 = (short)i; 9
Data types (2) ●
Rest of variables: reference types –
array,
–
classes, with the special case of String. String s = "This is a String.";
●
Reference types are compound objects: –
non-standard size,
–
we manipulate a reference to objects or arrays.
Java Lectures
10
Initialization ●
● ●
●
Primitive types: –
boolean: false,
–
char: '\0', i.e. 0,
–
byte, short, int, long, float, double: 0.
Reference types: null. Content of arrays initialized with default values. Local variables are not initialized.
Java Lectures
11
Expressions ●
The Java interpreter evaluates expressions: –
primary expressions: literals and variables, ●
–
ex: 1.7, true, sum.
more complex: operator to combine primary expressions. ●
assignment, arithmetic, String concatenation, comparison, boolean, bitwise and shift operators... –
●
ex: sum = 1+2, "Hel"+"lo".
order of evaluation (left to right), precedence, operand number and types, return types, side effects.
Java Lectures
12
Expressions (2) ●
Side effect: evaluating the expression changes the state of a Java program in such a way that evaluating the expression again may yield a different result. –
●
The evaluation will be the value itself. –
●
ex: i++, ++i, i+=2. ex: sum = 1+2 evaluates to 3.
Special: new, ., []...
Java Lectures
13
Statements ●
Single command executed by the Java interpreter, int counter; String message =
–
expression ...;
–
compound { }
–
labeled statement label : statement
–
local variables: all variables must be declared, and initialized, ● ●
"Hello";
final keyword: not allowed to change, (lexical) scope: variables can only be used within the method or block of code in which they are defined.
Java Lectures
14
Statements ●
●
●
Flow-control: –
conditionals: if/else, switch,
–
loops: while, do while, for, break (skip the end of a containing statement), continue (starts the next iteration of a loop).
Return statement: stops execution, implicit or explicit void return. Synchronized: protect critical sections (see Threads).
Java Lectures
15
Statements syntax ● ● ● ● ● ● ● ● ● ● ●
if (expr) statement [else statement]; switch (expr) { [case expr: statements] ... [default: statements] } while (expr) statement do statement while (expr); for (init; test; update) statement break [label]; continue [label]; return [expr];
Java Lectures
16
Exceptions ●
Exception: signal that indicates some sort of exceptional condition or error has occurred. –
throw an exception (object): signal an exceptional condition, which stops the normal program execution, propagates till it finds an exception handler.
–
type: java.lang.Throwable,
–
checked/unchecked: compiler checks.
if (situation1) throw an Exception of the type ExceptionSituation1 Java Lectures
17
Exceptions (2) try { ... if (condition1) return; ... if (condition2) throw new MyException(); ... } catch(MyException e) { ... } finally { ... } Java Lectures
18
Exceptions (3) ●
Exception handler: try/catch/finally statement, –
try: block of code that throws an exception, followed by 0 or more catch clauses,
–
catch(exception e){...}: handle various types of exceptions. The code looks for the first clause that has the argument of the same type as the exception.
–
finally: clean up code, guaranteed to be executed if any portion of the try block is executed (even if there is a break, continue, return statement).
Java Lectures
19
Methods ●
●
Named sequence of Java statements that can be invoked by other Java code. A method invocation is an expression.
modifiers type name (paramlist) exceptions] {...}
[throws signature
–
type: return type of the method, otherwise void,
–
name: not necessarily unique (overloading),
–
paramlist: 0 () or more,
–
throws: checked exception not handled.
Java Lectures
20
Classes ●
●
Named collection of –
fields that hold data values,
–
methods that operate on those values,
–
inner classes.
Every class is a new data type. –
data type (class) ≠ instances of that type (objects),
–
creation with new, special literals (and dynamic loading (serialization)),
–
Java Platform (1.4): over 1500 predefined classes.
Java Lectures
21
Simple class example class Point { //Fields int x, y; // Method that translates the point void translate(int h, int k) { x += h; y += k; } }
Java Lectures
22
Creating and using an object ●
In another class, we instantiate the class Point,
Point p = new Point(); p.x = 1; p.y = 3; p.translate(3,4); address of p
values of x and y 4
Java Lectures
7
Single specific instance, different from the class
23
Object literals ●
Special syntax for creating instances –
Strings: include text literally,
String myName = "Nicolas"; String sentence = "My name is" + myName; –
class Class: represents all Java types,
Class typePoint = Point.class; –
null: absence of object,
Point p = null; Java Lectures
24
Array types ●
Second kind of reference types in Java.
●
Numbered list of values, –
of any type, primitive, objects, even other arrays,
–
but all of the same types. int[] arrayOfIntegers; Point[] arrayOfPoints; int[][] arrayOfArrayOfIntegers;
●
Creating arrays with new. int[] arrayOfIntegers = new int[100];
Java Lectures
25
Using arrays ●
Access the individual values contained in the array: arrayName[index].
String responses = new String[2]; responses "Yes" "No" responses[0] = "Yes"; responses[1] = "No"; System.out.println("Answer " + responses[0] + " or " + responses[1] + " ! "); Answer Yes or No ! ●
For an array a, the first element is a[0], the second is a[1] and the last is a[a.length-1]. –
Exception ArrayIndexOutOfBoundsException.
Java Lectures
26
Array literals ●
Absence of array, null char[] password = null;
●
Specify array values literally,
int[] powersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128}; ●
Using anonymous arrays, Point[] arrayOfPoints = {new Point(), new Point(), new Point()};
Java Lectures
27
Multidimensional arrays class DoubleArray{ public static void main(String[] args){ int i,j; int[][] a = new int[2][3]; for (i = 0; i < a.length; i++) for (j = 0; j < a[i].length; j++) a[i][j] = i + j;
}
}
a = new int[2][]; for (i = 0; i < a.length; i++){ a[i] = new int[i + 2]; for (j = 0; j < a[i].length; j++) a[i][j] = -(i + j); }
Java Lectures
28
Multidimensional array literals
a
0
-1
-1
-2
-3
int[][] a = {{0, -1}, {-1, -2, -3}};
Java Lectures
29
Understanding reference types
Java Lectures
30
Using a constructor class Point{ int x, y; // Constructor Point(int a, int b){ x = a; y = b; } void translate(int h, int k) { x += h; y += k; } } Java Lectures
31
Example class TestNewPoint{ public static void main(String[] args){ Point p1 = new Point(2,3); Point p2 = new Point(-2,4); Point p3 = new Point(); p3 = p1; p1.translate(3,-2); System.out.println("Point p1: " + p1.x); System.out.println("Point p3: " + p3.x); } }
Point p1: 5 Point p3: 5
Java Lectures
32
Reference types p1
2
p3
p3 = p1;
3
p2
-2
4
then p1.translate(3,-2); p1 5 Java Lectures
p3
1 33
Reference types (2) ●
When arguments are passed to methods, the method is given a copy of the argument used to invoke the method. –
●
differences for primitive (not modified) and reference types (modified).
Make an actual copy of an object or an array, clone() method, –
no recursive copy.
Java Lectures
34
Reference types (3) Point p = new Point(1,2); Point q = (Point)p.clone(); q.translate(1,1);
Java Lectures
p
1
2
q
2
3
35
Comparing objects and arrays ●
Primitive types: ==
●
Reference types: –
== compares references to objects, not the content.
–
equals(): method to compare the contents, not implemented for all objects (otherwise equivalent to ==).
Java Lectures
36
Comparison example String letter = "o"; String s = "hello"; String copy = (String)s.clone(); String t = "hell" + letter; if (s==copy) System.out.println("same reference."); if (s==t) System.out.println("same reference."); if (s.equals(t)) System.out.println("same string."); same string.
Java Lectures
37
Packages ●
Named collection of classes (and possibly subpackages), –
● ●
namespace for the contained classes.
No #include, no link edition. Classes are loaded in the memory during compilation or execution.
Java Lectures
38
Packages (2) ●
The compiler and JVM need to find the necessary classes, –
use of import and globally unique class names,
–
use of classpath(s).
●
Packages, also useful for visibility levels.
●
Defining a package: package keyword.
●
Better to put every class in its own file, named A.java for class A.
Java Lectures
39
Import ●
Complete name of a class: Vector in java.util –
●
import: imports "nothing" –
●
java.util.Vector allows to use short names, for example Vector.
Exception: no need to import classes of the package java.lang.
Java Lectures
40
Java file structure package mypackage.test; import java.util.Vector; import java.io.*; class A{ ... } ●
●
File A.java
The complete name of class A is mypackage.test.A. The end of the name of the directory of A.java must be /mypackage/test/.
Java Lectures
41
Use of classpaths import mypackage.test.*; class B{ A local = new A(); ... }
File B.java in /mypackage/
●
javac -classpath ../ B.java
●
java -classpath ../ B
●
Or use environment variable CLASSPATH.
Java Lectures
42
Naming conventions ●
Packages: unique name with the prefixes, lowercase, –
●
Classes: the name begins with a capital letter, is written in mixed case, –
●
ex: java.lang.*.
ex: String, StringBuffer.
Interfaces: same as classes.
Java Lectures
43
Naming conventions (2) ●
Methods: the name begins with a lowercase letter, the following words with a capital letter. –
●
Fields and constants: same as method names for non constant fields, static final constants are written in uppercase. –
●
ex: insert(), insertObject(), insertObjectAt().
ex: MAX_VALUE.
Local variables: same conventions as methods and fields.
Java Lectures
44
Object Oriented Programming ●
All Java programs use objects, and every Java program is a class. –
classes,
–
class members: fields and methods,
–
constructors.
Java Lectures
45
Classes ●
●
●
Collection of data, members of a class, –
fields,
–
methods,
–
inner classes.
2 distinct types: –
class, or static: exists as soon the class is in memory, and is unique,
–
instance.
4 types of fields and methods.
Java Lectures
46
A class example public class Circle{ public static final double PI = 3.14159; public double r; public static double radiansToDegrees(double rads){ return rads * 180 / PI; } public double area(){ return PI * r * r; }
}
public double circumference(){ return 2 * PI * r; }
Java Lectures
47
Class fields ●
● ●
Associated with the class, rather than with an instance of the class: single copy. static modifier. final modifier: the value of the field does not change. It's a class constant (upper case), like a global variable. –
referred as PI in the class Circle,
–
referred as Circle.PI outside.
–
examples: Integer.MAX_VALUE, Color.red.
Java Lectures
48
Class methods ● ●
●
static modifier. Static methods can use only static members (field and methods: ex PI) of the class. Like a global function, invoked outside with the name of the class, double d = Circle.radiansToDegrees(2.0);
Java Lectures
49
Instance fields ●
Associated with instances of the class, –
every Circle object has its own copy of the double field r,
–
referred by name alone in the class (see circumference() and area()). Circle c = new Circle(); c.r = 2.0; Circle d = new Circle(); d.r = 2 * c.r;
●
instance constants with final (possible initialization in the constructor).
Java Lectures
50
Instance methods ●
An instance method operates on an instance of a class (an object), –
particular use of an instance method, Circle c = new Circle(); c.r = 2.0; double a = c.area(); no argument
–
can use any member of the class.
Java Lectures
51
How instance methods work ●
Implicit argument: this, holds a reference to the object. public double area(){ return PI * this.r * this.r; } public void setRadius(double r){ this.r = r; }
●
this cannot be used in class methods.
Java Lectures
52
Instance or class methods ●
It depends on their use. public static double area(double r){ return PI * r * r; }
–
●
With class methods, you do not need to create a Circle object.
This is an example of method overloading.
Java Lectures
53
Method overloading ●
●
A class can have several methods with the same name, differing –
on the type of their arguments,
–
on the number and order of their arguments.
–
A difference on the return type is not sufficient.
The compiler decides which method to invoke according to the arguments.
Java Lectures
54
Constructors Circle c = new Circle(); ●
Every class has at least one constructor. –
If none is implemented, there is a default constructor.
–
new creates a new, uninitialized instance of the class: the constructor method is then called, with the new object passed implicitly (this) and whatever arguments. Point p = new Point(1,2);
Java Lectures
55
Defining a constructor public Circle(double r) {this.r = r; }
●
–
The constructor name is always the same as the class name.
–
Unlike other methods, it is declared without a return type, not even void.
–
The body should initialize the this object.
Multiple constructors: method overloading. public Circle() {this.r = 1.0; }
Java Lectures
56
More with constructors ●
You can invoke one constructor from another, with this, public Circle(double r) {this.r = r; } public Circle() {this(1.0); } –
●
this avoids repetition of code,
Caution ! this(...) must appear as the first statement in a constructor.
Java Lectures
57
Another example public class Circle{ public static final double PI = 3.14159; public static int nbCircles = 0; public double r;
}
public Circle(double r) { this.r = r; Circle.nbCircles ++; }
We created 2 Circle objects.
public class TestCircle{ public void main(String[] args){ Circle c1 = new Circle(1.0); Circle c2 = new Circle(2.0); System.out.println("We created " + Circle.nbCircles + " Circle objects."); } }
Java Lectures
58
Field defaults and initializers ●
Unlike local variables, the fields of a class are automatically initialized to the default values, –
●
●
essentially 0 and null.
Class initialization methods for static members. Static and instance initializers, –
static {...} or {...}.
Java Lectures
59
Finalization and Garbage Collection ●
● ●
When an allocated object is no longer referred to by any other active object, the garbage collector finds and destroys it. Memory leaks can occur. Finalizer: instance method performing finalization for the object. void finalize() { ... tmpfile.delete(); }
Java Lectures
60
Subclasses and inheritance ●
Subclasses,
●
Constructor chaining,
●
Shadowing and overriding.
Java Lectures
61
Subclasses and inheritance ●
Central to the object-oriented programming paradigm. class B extends A { ... } –
A is the superclass of B.
–
B extends/subclasses A.
–
B has (inherits) all the non-private fields and methods of A, + its own fields and methods.
–
B is also an instance of class A.
Java Lectures
62
Inheritance example class Animal { int weight; public Animal(int weight) { this.weight = weight; } public void printWeight (){ System.out.println("This Animal weighs " + weight); } }
Java Lectures
63
Inheritance example (continued) class Spider extends Animal { int nbLegs; public Spider(int nbLegs) { super(5); this.nbLegs = nbLegs; }
This Animal weighs 5. This Spider has 8 legs.
public void printNbLegs (){ System.out.println("This spider has " + nbLegs + " legs."; } public static void main (String[] args) { Spider s = new Spider(8); s.printWeight(); s.printNbLegs(); } }
Java Lectures
64
The class hierarchy ●
Every class, except java.lang.Object, extends only one class, its superclass: NO multiple inheritance. –
Every class with no explicit superclass, except Object, extends automatically Object. Object Animal Spider
●
A class declared with the final modifier cannot be extended.
Java Lectures
65
Polymorphism and conversions ●
Every instance of Spider is also an Animal object, and of all classes higher in the hierarchy. –
widening conversion: the assignment of a Spider object to a Animal object is possible without a cast,
–
narrowing conversion: the opposite conversion needs a cast. The value held by the Animal object is still a valid Spider object.
Spider s = new Spider(); Animal a = s; Java Lectures Spider s2 = (Spider) a;
instanceof 66
Subclass constructors ● ●
super refers to the superclass. super(...) calls the constructor of the superclass. –
it can be used only within a constructor method,
–
it must be the first statement of the constructor.
Java Lectures
67
Constructor chaining ●
The constructor is called whenever an instance of any subclass is created. –
Java must ensure that every constructor calls its superclass constructor,
–
If the first statement of a constructor is not this (...) or super(...), Java implicitly inserts the statement super(),
– ●
constructor calls are chained.
Default constructor, super().
Java Lectures
class MyClass { public MyClass() { super(); } ... }
68
Constructor chaining example class A { A() { System.out.println("constructor of A"); } } class B extends A { B(){ System.out.println("constructor of B"); }
constructor of A constructor of B another constructor of B constructor of C
B(int r) { this(); System.out.println("another constructor of B"); } } class C extends B { C() { super(3); System.out.println("constructor of C"); }
}
public static void main(String[] args) { new C(); }
Java Lectures
69
Constructor chaining problem class A { int i; A(int i) { this.i = i; } }
What is the message of the compiler if we try to compile this file ?
class B extends A {} Essai.java:10: No constructor matching A() found in class A. class B extends A {} ^ 1 error
Java Lectures
70
Shadowing and polymorphism A, B and C have the same field x. In the methods of C,
A
x this.x super.x ((B)this).x ((A)this).x super.super.x
Field x in class C Field x in class C Field x in class B Field x in class B Field x in class A Illegal
c = new C(); c.x ((B)c).x ((A)c).x
Field x of class C Field x of class B Field x of class A
Java Lectures
B
C
Static link B contains the fields x of B and A.
71
Overriding superclass methods ●
● ●
When a class B defines an instance method using the same name, return type and parameters as a method in its superclass A, the method of B overrides the method of A. Overriding is not shadowing. Class methods, like fields, can be shadowed, but not overridden (different names). A.staticMethod(); B.staticMethod();
Java Lectures
72
Overriding is not shadowing class A { void className() { System.out.println("instance of class A"); } } class B extends A { void className() { System.out.println("instance of class B"); }
}
public static void main(String[] args) { A a = new A(); a.className(); a = new B(); instance a.className(); instance }
Java Lectures
of class A of class B 73
Dynamic method lookup ●
Process to look up at runtime the appropriate method to call for each objects. –
●
particularly useful for arrays of A objects.
Final methods, –
final methods: the method cannot be overridden by subclasses (same for final classes),
–
dynamic method lookup is more time consuming.
Java Lectures
74
Invoking an overridden method class B extends A { void className() { super.className(); System.out.println("instance of class B"); }
}
public static void main(String[] args) { B b = new B(); b.className(); instance of class A } instance of class B different from ((A)this).className()
Java Lectures
75
Invoking an overridden method (2) ●
●
The dynamic method lookup begins with the superclass. The super syntax can be used only to invoke an overridden method from within the class that overrides it. –
only the direct superclass.
–
different from the super() syntax to invoke a superclass constructor.
Java Lectures
76
Useful method overriding ●
The toString() method of Object.
class A { public String toString() { return("instance of class A"); } }
Created instances: instance of class A, instance of class B
class B { public String toString{ return("instance of class B"); }
}
public static void main(String[] args) { A a = new A(); B b = new B(); System.out.println("Created instances: " + a + ", " + b); }
Java Lectures
77
Encapsulation and access control
Java Lectures
78
Encapsulation ●
●
When all the data for a class is hidden, the methods define the only possible operations that can be performed on them (trusted use). –
hide implementation,
–
protect the class against misuse, for example by accessing directly the fields.
API classes, getValue(), setValue(), ...
Java Lectures
79
Access control ●
● ●
All the fields and methods of a class can always be used within the body of the class itself. –
rules for the use of the members outside of the class.
–
private, protected, package, public.
Access to packages: access to the files. Access to top-level classes within the package by default, everywhere if public.
Java Lectures
80
Access to members
accessible to defining class class in same package subclass in a different package non-subclass in different package
Java Lectures
public Yes Yes
member visibility protected package Yes Yes Yes Yes
private Yes No
Yes
Yes
No
No
Yes
No
No
No
81
Access control and inheritance ●
A class inherits all fields and instance methods (not constructor) of its superclass. –
the body of a class can always access all the fields and methods it declares itself,
–
it can also access the accessible members it inherits from its superclass.
–
a subclass in the same package inherits all nonprivate instance members.
–
a subclass in a different package inherits all protected and public instance members.
Java Lectures
82
Data accessor methods public class Circle { private int radius; public Circle(int r) { if (r > 0) radius = r; else radius = 0; } public int getRadius() { return radius; }
}
public void setRadius(int r) { if (r > 0) radius = r; }
Java Lectures
83
Encapsulation
public method public field private method private field
Access to private fields and methods is allowed only through public methods. Java Lectures
84
Abstract classes
Java Lectures
85
Abstract classes ●
Method with only the signature: –
●
Class declaring an abstract method: –
●
abstract method, must be declared abstract. abstract class, must be declared abstract.
An abstract class cannot be instantiated, –
it must be extended to be used,
–
a subclass is still abstract if she does not implement all the abstract methods it inherits.
Java Lectures
86
Remark ●
Since they cannot be overridden, –
static, private, final methods cannot be abstract,
–
a final class cannot contain any abstract methods.
Java Lectures
87
Abstract classes example abstract class Shape { abstract double perimeter(); abstract double area(); } class Circle extends Shape { public static final double PI = 3.1415926535; protected double r; public Circle(double r) { this.r = r; } public double getRadius() { return r; } public double area() { return PI*r*r; } public double perimeter() { return 2*PI*r; } }
Java Lectures
88
Abstract classes example (continued) class Rectangle extends Shape { protected double w, h; public Rectangle(double w, double h) { this.w = w; this.h = h; } public double getWidth() { return w; } public double getHeight() { return h; } public double area() { return w*h; } }
public double perimeter() { return 2*(w + h); }
Java Lectures
89
Use of abstract classes Shape[] shapes = new Shape[3]; shapes[0] = new Circle(2.0); shapes[1] = new Rectangle(1.0, 3.0); shapes[2] = new Rectangle(4.0, 2.0); double total_area = 0; for (int i = 0; i < 3; i++) total_area += shapes[i].area(); ●
Every Shape object is guaranteed to have implementations of the abstract methods, –
polymorphism,
–
dynamic method lookup.
Java Lectures
90
Alternative ? ●
Why would it be worse to declare the Shape class like that ? class Shape { float perimeter() { return 0; } float area() { return 0; } }
Java Lectures
91
Interfaces
Java Lectures
92
Interfaces ●
Sometimes, you would like to extend more than one class, –
solution: a class can implement any number of interfaces,
–
new reference type, similar to classes. Interface can extend more than one interfaces,
–
no implementation, contains only ● ●
–
method signatures: methods are implicitly abstract, constant definitions (static final).
interfaces can not be instantiated (no constructor).
Java Lectures
93
Implementing an interface ●
A class A implements an interface I, –
provides an implementation for each method of I (of all the implemented interfaces). Otherwise, A inherits all the unimplemented abstract methods, and must be declared itself abstract,
–
inherits the constants (interfaces for set of constants).
–
all members are implicitly public, the class must declare all inherited methods public.
–
all subclasses of A implement the interface I.
Java Lectures
94
Interface example public interface Centered { public void setCenter(double x, double y); public double getCenterX(); public double getCenterY(); } public class CenteredRectangle extends Rectangle implements Centered { private double cx, cy; public CenteredRectangle(double cx, double cy, double w, double h) { super(w, h); this.cx = cx; this.cy = cy; } public void setCenter(double x, double y) { cx = x; cy = y; } public double getCenterX() { return cx; } public double getCenterY() { return cy; } }
Java Lectures
95
Other interface examples ●
CenteredRectangle objects are also instances of Centered and Shape.
class CenteredScalableRectangle extends Rectangle, implements Centered, Scalable { ... } ●
Marker interfaces: additional information. –
ex: Cloneable interface.
Java Lectures
96
Inner classes
Java Lectures
97
Inner classes overview ●
So far, top-level classes and interfaces, –
●
direct members of packages, not nested within other classes.
4 types: –
static member classes (or interfaces),
–
member classes,
–
local classes,
–
anonymous classes.
Java Lectures
98
Some features ●
●
●
No static members within inner classes, except constant fields (static final). Not the same name as any enclosing class. or package. Since they are members of the class, static member classes and member classes can have their own access control modifier (public, protected and private, or default package).
Java Lectures
99
Static member classes ●
●
Class or interface, defined as static member of another class. Behaves like an ordinary top-level class, –
except that it can access all the static members of the enclosing class (without class name), even other static member classes,
–
(reverse) the methods of the enclosing class have access to all the members of a static member class.
Java Lectures
100
Static member classes example public class LinkedStack { public static interface Linkable { public Linkable getNext(); public void setNext(Linkable node); } Linkable head; public void push(Linkable node) {...} public Object pop() {...} } class LinkableInteger implements LinkedStack.Linkable { int i; public LinkableInteger(int i) { this.i = i; } LinkedStack.Linkable next; public LinkedStack.Linkable getNext() { return next; } public void setNext(LinkedStack.Linkable node) { next = node; } }
Java Lectures
101
Member classes ●
●
Defined as a member of an enclosing class, not declared with the static modifier. Associated with instances of the enclosing class, –
therefore has access to all the fields and methods of the enclosing class (static and non-static). current = head; this.current = LinkedStack.this.head;
–
class hierarchy ≠ containment hierarchy.
Java Lectures
102
Member classes example public class LinkedStack { public static interface Linkable {...} private Linkable head; public void push(Linkable node) {...} public Linkable pop() {...} public java.util.Enumeration enumerate() { return new Enumerator(); }
}
protected class Enumerator implements java.util.Enumeration { Linkable current; public Enumerator() { current = head; } public boolean hasMoreElements() { return (current != null); } public Object nextElement() { if (current == null) throw new java.util.NoSuchElementException(); Object value = current; current = current.getNext(); return value; } }
Java Lectures
103
Local classes ●
●
Defined locally, within a block of Java code, –
Java statement,
–
visible only within that block.
Same access as member classes, –
in addition, access to local variables, method parameters, or exception parameters in its scope, but only final (possible different lifetimes, copy of the containing class).
Java Lectures
104
Local classes example public java.util.Enumeration enumerate() { class Enumerator implements java.util.Enumeration { Linkable current; public Enumerator() { current = head; } public boolean hasMoreElements() { return (current != null); } public Object nextElement() { if (current == null) throw new java.util.NoSuchElementException(); Object value = current; current = current.getNext(); return value; } } return new Enumerator(); }
Java Lectures
105
Anonymous classes ●
Local class without a name. –
Java expression (not a statement like local classes): defined and instantiated in a single succinct expression using the new operator.
–
provide a simple implementation of an adapter class (its code is invoked by some other object).
File f = new File("/src"); String[] filelist = f.list(new FilenameFilter() { public boolean accept(File f, String s) {return s.endsWith(".java");} });
Java Lectures
106
Anonymous classes (2) –
No implement or extend. If the name is the name of a class or an interface, the anonymous class implicitly extends or implements it.
–
It uses the superclass constructor: you can use instance initializer "instead of" a constructor.
–
Same restrictions as local classes.
Java Lectures
107
Anonymous classes example public java.util.Enumeration enumerate() { return new java.util.Enumeration() { Linkable current; { current = head; } public boolean hasMoreElements() { null); } public Object nextElement() { if (current == null) throw new java.util.NoSuchElementException(); Object value = current; current = current.getNext(); return value; } }; } Java Lectures
return (current !=
108
Exceptions revisited
Java Lectures
109
More on Exceptions class Animal{} class Spider extends Animal { int weight = 5; }
A spider weighs 5 g. java.lang.ClassCastException: Animal, every Animal is not a Spider.
class Conversion { public static void main(String argv[]) { Animal animal = new Spider(); System.out.println("A spider weighs: " + ((Spider)animal).weight + " g."); animal = new Animal(); try { Spider spider = (Spider)animal; } catch (ClassCastException e) { System.out.println(e +", every Animal is not a Spider."); } } } Java Lectures 110
Class Exception ●
The type of a Java exception is java.lang.Throwable, with 2 standard subclasses, –
java.lang.Error: unrecoverable problems, unchecked,
–
java.lang.Exception: less severe, checked (except RuntimeException).
Java Lectures
111
Exception definition example class ExceptionNothing extends Exception { int nbWords; ExceptionNothing(int number) { nbWords = number; } public String toString() { return "ExceptionNothing: none of the " + nbWords " marks is valid."; } }
Java Lectures
112
class TestThrowExceptions { static int average(String[] list) throws ExceptionNothing { int i, sum=0, integer, nbMarks=0; for (i = 0; i < liste.length; i++) { try { nbMarks++; integer = Integer.parseInt(list[i]); sum += integer; } catch (NumberFormatException e) { System.out.println("The " + (i+1) + " nth mark is not an integer."); } } if (nbMarks == 0) throw new ExceptionNothing(list.length); return sum/nbMarks; java TestThrowException ha 15.5 } public static void main(String[] argv){ try { System.out.println("The average is " + average(argv)); } catch (ExceptionNothing e) { System.out.println(e); } } The 1 nth mark is not an integer. } The 2 nth mark is not an integer. ExceptionNothing: none of the 2 marks is valid.
Java Lectures
113
Propagation ●
If your method calls another that can throw a checked exception, you must –
either include exception-handling code,
–
or use throws to declare that your method can also throw that exception. That's how an exception is propagated until it is caught.
Java Lectures
114
Propagation example ... method1() throws MyException { ... if (...) throw new MyException(); ... }
... method2() throws MyException { ... zzz.method1(); ... }
... method3() { ... try { ... yyy.methode2(); ... } catch(MyException e) { ... } ... } ... method4() { ... xxx.method3(); ... }
Java Lectures
115
Useful APIs ●
Strings,
●
Input/Output streams,
●
Threads,
●
Network.
Java Lectures
116
Strings
Java Lectures
117
String class ●
java.lang.String class.
●
String object are immutable, –
methods return new String objects.
–
easy use of regular expressions: same regex syntax as the Perl programming language (otherwise java.util.regex package).
String s = "Good morning !"; String s1 = s.substring(0,4); // "Good" s1.compareTo("Good"); // 0 s.matches("[A-Z].*[.?!]$"); // true Java Lectures
118
Useful classes ●
Character class, –
●
StringBuffer class, –
●
check the type and convert the case. String objects are immutable, but not StringBuffer objects.
java.util.StringTokenizer class, –
to break a string of text into its component words: it implements Enumeration.
Java Lectures
119
Input/Output streams ●
And the java.io package.
Java Lectures
120
Files and directories ●
java.io.File.
●
know the content of a directory.
●
work with paths.
●
create, rename, suppress a file or a directory.
Java Lectures
121
Input/Output streams ●
●
The java.io package defines a large number of classes for reading and writing streaming, or sequential, data. Processing streams of bytes, –
●
InputStream and OutputStream.
Processing streams of characters, –
Reader and Writer.
Java Lectures
122
Two types of classes ●
Extraction classes –
●
read or write data in some type of container (File, String, arrays of bytes, socket...).
Functionality classes –
let us act on the data streams, independently of the container (read a line, read an integer...).
Java Lectures
123
Output data streams
program data OutputStream functionality Writer functionality program
Java Lectures
byte char
OutputStream extraction Writer extraction
File socket… destination
124
Input data streams
program data InputStream functionality File, socket… source
Java Lectures
InputStream extraction Reader extraction
byte char
Reader functionality program
125
Subclasses of Reader CharArrayReader
StringReader
PipedReader
Reader BufferedReader
FilterReader
InputStreamReader
LineNumberReader
PushbackReader
FileReader
extraction classes Java Lectures
functionality classes
126
Subclasses of Writer PrintWriter
FilterWriter
StringWriter
PipedWriter
Writer BufferedWriter
OutputStreamWriter
CharArrayWriter
FileWriter
extraction classes Java Lectures
functionality classes
127
Reading console input BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is your name ?"); String name = null; try { name = console.readLine(); } catch (IOException e) { name = ""; } System.out.println("Hello " + name); InputStream Sytem.in Java Lectures
Hello Nicolas 128
Reading lines from a text file String filename = "myfile.txt"; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String line; while((line = in.readLine()) != null) { System.out.println(line); } in.close(); } catch (IOException e) { ... } Java Lectures
129
Writing text to a file try { File f = new File("myresultfile.txt"); PrintWriter out = new PrintWriter(new FileWriter(f)); out.println("No result for now."); out.close(); } catch (IOException e){...}
Java Lectures
130
Direct subclasses of InputStream and some other classes StringBuffer InputStream
ByteArray InputStream
Piped InputStream
Sequence InputStream
InputStream FileInputStream
FilterInputStream
BufferedInputStream
ObjectInputStream
DataInputStream
extraction classes Java Lectures
functionality classes
131
Direct subclasses of OutputStream and some other classes ByteArrayOutputStream
PipedOutputStream
OutputStream FileOutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream
PrintStream
DataOutputStream
extraction classes Java Lectures
functionality classes
132
Writing a binary file try { DataOutputStream out = new DataOutputStream (new BufferedOutputStream (new FileOutputStream("test.data"))); out.writeUTF("Start"); out.writeInt(765); out.writeLong(54321); out.writeFloat((float)2.35); out.writeDouble(1.8); out.writeChar('a'); out.writeBoolean(false); out.writeChars("good bye"); System.out.println(out.size()); // 50 out.close(); } catch (IOException e) {...}
Start ý Java Lectures
Ô1@ff?üÌÌÌÌÌÍ a
g o o d
b y e 133
Reading a binary file try { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("test.data"))); System.out.println(in.readUTF()); System.out.println(in.readInt()); Start System.out.println(in.readLong()); 765 System.out.println(in.readFloat()); System.out.println(in.readDouble()); 54321 System.out.println(in.readChar()); 2.35 System.out.println(in.readBoolean()); 1.8 while (in.available() > 0){ a System.out.print(in.readChar()); false } good bye in.close(); } catch (IOException e) {...}
Java Lectures
134
Serialization ●
●
Convert an object into a stream of bytes that can later be deserialized back into a copy of the original object. –
write serialized objects in any type of stream: files, sockets...
–
To serialize an object, its class must implement the interface java.io.Serializable.
Functionality classes: –
ObjectOutputStream: writeObject(),
–
ObjectInputStream: readObject().
Java Lectures
135
import java.io.*; class ClassTest implements Serializable { String s = "Hello"; int n = 1; } class Serialization { public static void main(String[] argv) { ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("test.data")); out.writeObject(new ClassTest()); int[] array = {10, 11, 12}; out.writeObject(array); out.close(); ObjectInputStream in = new ObjectInputStream (new FileInputStream("test.data")); ClasseTest c = (ClassTest)in.readObject(); System.out.println(c.s + " " + c.n); int[] arrayout = (int[])in.readObject(); System.out.println(arrayout[1]); in.close(); } }
Java Lectures
Hello 1 11
136
Threads ●
A thread is a single sequential flow of control within a program.
Java Lectures
137
Thread definition ●
2 ways to create a java.lang.Thread object: –
subclass Thread, override the run() method, then instantiate your Thread subclass,
–
define a class that implements the Runnable interface (i.e. define a run() method), then pass an instance of this Runnable object to the Thread() constructor.
–
The run() method constitutes the body of the thread.
Java Lectures
138
Thread example final List list // initialized elsewhere class BackgroundSorter extends Thread { List l; public BackgroundSorter(List l) {this.l = l;} public void run() {Collections.sort(l);} } Thread sorter = new BackgroundSorter(list); sorter.start(); Thread t = new Thread(new Runnable{ public void run() {Collections.sort(list);} }); t.start(); Java Lectures
139
Explanation Original thread
new thread
... Thread sorter = new BackgroundSorter(list); sorter.start();
Meanwhile, it continues running Thread t = new Thread(new Runnable{ public void run() {Collections.sort(list);} }); t.start();
creation executes the run() method. Collections.sort(l);
ceases to exist when the run() method exits.
... Java Lectures
140
Some thread methods ● ●
●
Threads can run at different priority levels. Make a thread sleep with the sleep() method. Wait for a thread to finish with the join() method.
Java Lectures
141
Thread synchronization ●
●
Thread synchronization, –
access the same data structure,
–
every java object has a lock associated to it: when a thread holds the lock, another thread has to wait for the first one to release the lock.
synchronized keyword, –
a thread must obtain a lock on an object before it can execute any of its synchronized methods,
–
synchronized blocks that holds a lock on a specified object for a short time.
Java Lectures
142
synchronized example public class CubbyHole { public synchronized int get() { ... } public synchronized void put(int value) { ... } } Whenever the program enters a synchronized method, the thread that called the method locks the object whose method has been called. ... synchronized(resource1) {...} ... Java Lectures
143
Thread coordination ●
Problem of deadlocks.
●
Coordinate threads with Object methods, –
wait(): any lock the thread holds is temporarily released, the thread is added to the list of waiting threads for that object and stops running,
–
notify(): the objects wakes up one of the waiting threads and allows it to continue running.
Java Lectures
144
Network: Sockets ●
the java.net package.
Java Lectures
145
the URL class ●
Uniform resource locator, supports at least http://, ftp:/ and file://.
URL url; try { url = new URL("http:", "perso.enst.fr/~saunier", "index.html"); } catch (MalformedURLException e) {...} InputStream in = url.openStream(); URLConnection conn = url.openConnection(); String type = conn.getContentType(); String encoding = conn.getCOntentEncoding(); java.util.Date lastModified = new java.util.Date (conn.getLastModified()); int len = conn.getContentLength();
Java Lectures
146
Sockets ●
Software endpoint that establishes bidirectional communication between –
a server program (specific hardware port),
–
and one or more client programs: any client program anywhere in the network with a socket associated with that same port can communicate with the server program.
Java Lectures
147
Socket example import java.io.*; import java.net.*; public class HttpMirror { public static void main(String[] args) { try { int port = Integer.parseInt(args[0]); ServerSocket ss = new ServerSocket(port); for(;;) { Socket client = ss.accept(); ClientThread t = new ClientThread(client); t.start(); } } catch (Exception e) { System.err.println(e.getMessage()); System.err.println("Usage: java HttpMirror ;"); } }
Java Lectures
148
static class ClientThread extends Thread { Socket client; ClientThread(Socket client) { this.client = client; } public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream())); out.print("HTTP/1.0 200\r\nContent-Type: text/plain\r\n\r\n"); String line; while((line = in.readLine()) != null) { if (line.length() == 0) break; out.println(line); } out.close(); in.close(); client.close(); } catch (IOException e) {...} } } } Java Lectures
149
Sockets ●
●
javax.net.* and java.net.ssl.* enable encrypted network communication over sockets that use the Secure Sockets Layer protocol. If you don't care to maintain a stream, –
DatagramSocket and DatagramPacket classes.
Java Lectures
150
Swing
Java Lectures
151
Java 1.5
Java Lectures
152