Introduction à la programmation Java

Transcription

Introduction à la programmation Java
Programmation 2
Introduction à la programmation Java
Course information
• Lectures: 6 x 2 hours
• TPs: 6 x 2 hours
• Lecturer: Alexandru Costan
alexandru.costan at inria.fr
• TP instructor: Delphine Demange
delphine.demange at irisa.fr
Contents
• Introduction to Java programming language
• Inheritance and applications
• Introduction to Swing
• Swing interactions
• Threads
• Perspectives
Readings
•
•
•
Main references (Sun)
•
•
•
•
The Java Language Specification
The Java Virtual Machine Specification
The Java Tutorial Books
Java Series Books (on the Sun website)
Further readings
•
•
•
•
Le langage Java: Concepts et pratique -le JDK 5.0, Irène Charon
•
Algorithms in Java: Fundamentals, Data Structures, Sorting, Searching, and Graph
Algorithms, Robert Sedgewick
Introduction à la programmation objet en Java: Cours et exercices, Jean Brondeau
Algorithmique et programmation en Java: Cours et exercices corrigés,Vincent Granet
Java 2.0: De l'esprit à la méthode, Michel Bonjour, Gilles Falquet, Jacques Guyot, André
Le Grand
Course website
•
http://www.irisa.fr/celtique/demange/ens/prog2/
Evaluation
• Small project: 20%
• Main project: 50%
• Written exam: 30%
Introduction to Java
programming language
History
•
•
•
1991: developed by Sun Microsystems as a small
programming language for embedded household
devices
•
Initially called Oak
1995: Java 1.0 released
•
•
“Write Once, Run Anywhere”
Became popular with webpages running applets
1997: Standard
•
•
SDK
JRE
History
•
•
•
•
1998: Java 1.2, multiple types of platforms
•
•
•
J2EE
J2ME
J2SE
2004: Java 5
•
•
Collections, enumerate
concurrent programming
2006: open source, GPL
•
Sun: "Java's evangelist"
Nowadays, widely accepted as a multi-purpose programming
language / technology
•
•
Portable, safe
Object-oriented, component-oriented
Why Java?
•
•
•
•
Easy to use
•
•
•
Addresses the weaknesses of older programming languages
Object-oriented
Supports good programming styles
Portability - Interpreter environment
Safe
•
•
Data always initialized, references always type-safe
Access to "private" or "package private" data and methods is
rigidly controlled.
Features
•
Built-in multi-threading
Compiling and interpreting
•
•
Program source code compiled into bytecode
Bytecode is executed in an interpreter environment
(Virtual Machine)
Java VM for
Windows
Java
program
.java
Compiler
Java
bytecode
program
.class
Java VM for
Linux
Java VM for
Mac OS
Types of Java applications
•
•
•
•
•
Desktop application - J2SE
•
Java Application: normal Java application running on
desktops; console or GUI
•
Java Applet: embedded application running within Web
browsers
Server application - J2EE
•
JSP, Servlets
Mobile (embedded) application – J2ME
Java Card
Java RMI - distributed programming
Types of Java applications
•
•
•
•
•
Desktop application - J2SE
•
Java Application: normal Java application running on
desktops; console or GUI
•
Java Applet: embedded application running within Web
browsers
Server application - J2EE
•
JSP, Servlets
Mobile (embedded) application – J2ME
Java Card
Java RMI - distributed programming
Object Oriented Programming
• Procedural programming
vs. OOP
• Limitations of procedural
programming:
•
•
•
Data are separated from processes
•
Difficulty in code maintenance
Passive data, active processes
No guarantee of data consistancy
and constrainsts
Object Oriented Programming
•
•
Addresses these limitations
•
•
•
Guarantee of data consistency
•
Create a “type”(class) for these
objects so that you don’t have to
redo all the work in defining an
objects properties and behavior
Data come together with
related processing code
Easier maintenance
Define “things”(objects) which
can either do something or have
something done to them
Hello World
•
•
•
Compile: javac TestGreeting.java
Run: java TestGreeting
Result: Hello, world
Classes
• Are the templates to create objects (by
instantiation)
• Each object has the same structure and
behavior as the class from which it was
created
Declaring a class
public class CLASSNAME {
}
Declaring a class
public class CLASSNAME {
fields
methods
}
Classes
• Definition
• Instance
Constructors
•
Every class has a special “method”(s) called constructor to
initialise objects’ data members
•
A constructor is invoked when an object is to be “created”/
“allocated” by using the new operator
Baby myBaby1 = new Baby();
•
A class may have multiple constructors (overloading)
•
Distinguished at compile time by having different parameter lists
Baby myBaby2 = new Baby("Madonna", false);
Baby myBaby3 = new Baby("Bono", 2.5);
•
When no constructors are defined in source code, a
default constructor that requires no arguments and does
nothing will be automatically provided.
Constructors
public class Baby{
String name;
boolean isMale;
double weight;
public Baby(){
name = "John Doe";
isMale = true;
weight = 3.1;
}
public Baby(String babyName, boolean gender){
name = babyName;
isMale = gender;
weight = 3.1;
}
public Baby(String babyName, double kilos){
name = babyName;
isMale = true;
weight = kilos;
}
}
Access modifiers
•
•
public: Accessible anywhere by anyone
•
private: Only accessible within the
current class
•
default (no keyword): accessible within the
current package
protected: Accessible only to the class
itself and to its subclasses or other classes in
the same “package”
Data types
•
•
•
Java is a strongly typed language
•
•
Every variable must have a declared type
There are two kinds of data types
Primitive data types
•
•
Variables are manipulated via variable names
int a = 5;
Reference types
•
•
•
Arrays and objects
Manipulated via references
GradeBook myGradeBook = new GradeBook();
Primitive data types
Assignment operator “=“
Baby tom = new Baby("Tom", 2);
Baby alex = new Baby("Alex", 3);
tom = alex
alex.weight = 5;
System.out.print(tom.weight);// 5
• Copy the reference's content, NOT the
referred object
Assignment operator “=“
Baby tom = new Baby("Tom", 2);
Baby alex = new Baby("Alex", 3);
tom = alex
alex.weight = 5;
System.out.print(tom.weight);// 5
• Copy the reference's content, NOT the
referred object
Reference types
public class Baby{
String name;
boolean isMale;
double weight;
public Baby(){
name = "John Doe";
isMale = true;
weight = 3.5;
}
public void eat(double food){
weight = weight + food;
}
Heap memory
a Baby object
Baby tom
name
isMale
weight
Baby tom;
tom = new Baby();
tom.eat(2.1);
•
•
•
•
•
•
Objects are manipulated via references
Object references store object locations in computer’s memory
NO explicit pointers in Java (no direct access to the references)
NO pointer operators
Directly handle attributes and methods
Assignments (=) of references do NOT copy object’s content
Equality operators: “==“and “!=“
• Compare the content of the variables
•
•
Value of primitive data
Value of references
•
i.e. check if they point to the same object, NOT whether the content
of the objects are the same
int n1 = 1;
int n2 = 1;
System.out.println(n1 == n2); //true
Baby baby1 = new Baby("Tom");
Baby baby2 = new Baby("Tom");
System.out.println(baby1 == baby2); //false
Equality operators: “==“and “!=“
• Compare the content of the variables
•
•
Value of primitive data
Value of references
•
i.e. check if they point to the same object, NOT whether the content
of the objects are the same
int n1 = 1;
int n2 = 1;
System.out.println(n1 == n2); //true
Baby baby1 = new Baby("Tom");
Baby baby2 = new Baby("Tom");
System.out.println(baby1 == baby2); //false
Equality operators: “==“and “!=“
• Compare the content of the variables
•
•
Value of primitive data
Value of references
•
i.e. check if they point to the same object, NOT whether the content
of the objects are the same
int n1 = 1;
int n2 = 1;
System.out.println(n1 == n2); //true
Baby baby1 = new Baby("Tom");
Baby baby2 = new Baby("Tom");
System.out.println(baby1 == baby2); //false
Garbage collection
•
To reclaim the memory occupied by objects that are no
longer in use
•
•
Programmers don’t have to deallocate objects
•
Java Virtual Machine (JVM) performs automatic garbage
collection
•
•
Method finalize() is called by JVM, not by programmers
Guarantees no memory leaks
However, there’s no guarantee when/whether an object is
freed before the program terminates
•
•
Might not be needed as memory is still available
Clean-up tasks must be done explicitly by other “clean-up” methods
The this reference
•
this: the reference that points to the current object
(from inside).
•
usage of this:
•
•
•
explicit reference to object’s attributes and methods
parameter passing and return value
calling constructor from inside constructor
The this reference
•
this: the reference that points to the current object
(from inside).
•
usage of this:
•
•
•
explicit reference to object’s attributes and methods
parameter passing and return value
calling constructor from inside constructor
Static types and methods
• Applies to fields and methods
• Means the field/method
• is defined for the class declaration
• is not unique for each instance
• Static methods
• can't access non-static attributes
• can't call non-static methods
Packages
•
•
Each class belongs to a package
•
•
•
Packages are just directories
•
Classes in the same package serve a similar
purpose
Classes in other packages need to be imported
All classes "see" classes in the same package
(no import needed)
All classes "see" classes in java.lang
•
ex: java.lang.String; java.lang.System
Packages
•
Definition
package path.to.package.foo;
class Foo{
...
}
•
Usage
import path.to.package.foo.Foo;
import path.to.package.foo.*;
•
Specific packages
java.lang, java.util, java.io, java.awt,
java.net, java.applet
Standard I/O
•
Three stream objects automatically created when a
Java program begins executing
•
System.out: standard output stream object
•
•
•
normally enables a program to output data to the screen
(console)
•
ex: System.out.println("some text");
System.err: standard error stream object
•
normally enables a program to output error messages to the
screen
System.in: standard input stream object
•
normally enables a program to input bytes from the keyboard
Arrays
• Indexed list of values: TYPE[]
• The index starts at 0 and ends at length-1.
int[] values;
values = new int[5];
int size = values.length;
int[][] M = new int[3][2];
int[] primes = {1,2,3,5,7};
Strings
• String - constant strings (non-modifiable)
String ch1 = new String("bonjour");
String ch2 = "au revoir";
String ch3 = ch1+ch2;
int i = ch1.indexOf('j');
char c = ch2.charAt(3);
• StringBuffer - mutable strings
StringBuffer sb1 = new StringBuffer(ch1);
sb1.append('x');
sb1.insert(3,"yyy");
Constant data
• final attribute
•
•
primitive data types: constant values
reference types: constant references
final int number = 7;
number = ...; //NO!
number++; //NO!
final Robot R2D2 = new Robot();
R2D2 = ...; //NO!
R2D2.positionX = 15; //YES!
R2D2.positionY = 20; //YES!
Constant data
• final attribute
•
•
primitive data types: constant values
reference types: constant references
final int number = 7;
number = ...; //NO!
number++; //NO!
final Robot R2D2 = new Robot();
R2D2 = ...; //NO!
R2D2.positionX = 15; //YES!
R2D2.positionY = 20; //YES!
Constant data
• final attribute
•
•
primitive data types: constant values
reference types: constant references
final int number = 7;
number = ...; //NO!
number++; //NO!
final Robot R2D2 = new Robot();
R2D2 = ...; //NO!
R2D2.positionX = 15; //YES!
R2D2.positionY = 20; //YES!
Constant data
• final attribute
•
•
primitive data types: constant values
reference types: constant references
final int number = 7;
number = ...; //NO!
number++; //NO!
final Robot R2D2 = new Robot();
R2D2 = ...; //NO!
R2D2.positionX = 15; //YES!
R2D2.positionY = 20; //YES!
Constant data
• final attribute
•
•
primitive data types: constant values
reference types: constant references
final int number = 7;
number = ...; //NO!
number++; //NO!
final Robot R2D2 = new Robot();
R2D2 = ...; //NO!
R2D2.positionX = 15; //YES!
R2D2.positionY = 20; //YES!
Constant data
• final attribute
•
•
primitive data types: constant values
reference types: constant references
final int number = 7;
number = ...; //NO!
number++; //NO!
final Robot R2D2 = new Robot();
R2D2 = ...; //NO!
R2D2.positionX = 15; //YES!
R2D2.positionY = 20; //YES!
Exception handling
If a method p() uses a method q() susceptible to trigger an exception:
• catch and handle the exception
void p(){ ...
try { ... q() ...}
catch(xxxException e){//handling e}
}
•
or, propagate the exception
void p() throws xxxException{ ... q() ...}
xxxException: derived from Exception or RuntimeException
ex: IOException, NullPointerException,
NumberFormatException, IndexOutOfBoundsException
finally{ ... } associated with a try{...} block, typically for
cleanup purposes (closing files, freeing resources)
Create your own exceptions
•
•
By extending the java.lang.Exception class
Typically define constructor(s) and redefine the toString()
method
public class ExceptionRien extends Exception {
int nbChaines;
public ExceptionRien(int nombre) {
nbChaines = nombre;
}
public String toString() {
return "ExceptionRien : aucune des " + nbChaines + "
chaines n'est valide";
}
}
•
Usage:
... throw new ExceptionRien();
To take away
• object oriented programming language
• data centric
• classes: models; objects: instances
• objects handled through references
• extensive API