• No results found

Programmation 2. Introduction à la programmation Java

N/A
N/A
Protected

Academic year: 2021

Share "Programmation 2. Introduction à la programmation Java"

Copied!
40
0
0

Loading.... (view fulltext now)

Full text

(1)

Programmation 2

(2)

Course information

CM: 6 x 2 hours

TP: 6 x 2 hours

CM: Alexandru Costan alexandru.costan at inria.fr

TP: Vincent Laporte vincent.laporte at irisa.fr

(3)

Contents

Introduction to Java programming language

Graphical interfaces: Swing

Threads

Network communication and Internet Java

programming

Programming with Big Data: Hadoop Map

(4)

Readings

Main references (Oracle)

• The Java Language Specification

• The Java Virtual Machine Specification

• The Java Tutorial Books

• Java Series Books

Further readings

• Le langage Java: Concepts et pratique -le JDK 5.0, Irène Charon

• 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

• Algorithms in Java: Fundamentals, Data Structures, Sorting, Searching, and Graph Algorithms, Robert Sedgewick

Course website

(5)

Evaluation

Project: 70%

(6)

Introduction to Java

programming language

(7)

History

1991: developed by Sun as a small programming language for embedded household devices

1995: Java 1.0 released

“Write Once, Run Anywhere”

Became popular with webpages running applets

1997: Standard - SDK, JRE

1998: Java 1.2 - J2EE, J2ME, J2SE

2004: Java 5 - Collections, Enumerate, Concurrent

2014: Java 8

James Gosling - designer of Java

(8)

Why Java?

Easy to use

Addresses the weaknesses of older programming languages

Object-oriented

Supports good programming styles

Portability

Interpreter environment

Safe

Data always initialised, references always type-safe

Features

(9)

Java vs. C based OOP

C++

pointers

machine dependent

no memory management support

C#

different support for generics

no checked exceptions

(10)

Compiling and interpreting

Program source code compiled into bytecode

Bytecode is executed in an interpreter environment (Virtual Machine)

Java program .java Compiler Java bytecode program .class Java VM for Windows Java VM for Linux Java VM for Mac OS

(11)

Hello World

Compile: javac TestGreeting.java

Run: java TestGreeting

(12)

Access modifiers

public: Accessible anywhere by anyone

protected: Accessible only to the class

itself and to its subclasses or other classes in the same “package”

private: Only accessible within the current

class

default (no keyword): accessible within the current package

(13)

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;

have wrapper types: int/Integer, char/Character, double/Double etc.

Reference types

Arrays and objects

Manipulated via references

(14)

Reference types

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

public class Baby{ String name; boolean isMale; int weight;

public Baby(String n, int w){ name = n;

isMale = true; weight = w; }

Baby tom = new Baby(“Tom”,2); Baby alex = new Baby(“Alex”,3); tom = alex;

alex.weight=5;

System.out.print(tom.weight);

Baby tom name

isMale weight

a Baby object

(15)

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");

(16)

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

(17)

Packages

Each class belongs to a package

Classes in the same package serve a similar purpose

Packages are just directories

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

(18)

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

(19)

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

(20)

Strings

String - constant strings (non-modifiable)

String r = “essai”;

String s = “es”+”sai”;

String t = “ESSAI”.toLowerCase(); int i =r.indexOf('i');

char c = s.charAt(3);

int comp =r.compareTo(s); boolean test1 = (r==s); boolean test2 = (r==t)

StringBuffer - mutable strings

StringBuffer sb1 = new StringBuffer(ch1); sb1.append('x');

(21)

Static types and methods

Applies to fields and methods

Means the field/method

is defined for the class declaration

is unique for all instances

Static methods

can't access non-static attributes

(22)

Constant data

final keyword

primitive data types: constant values

reference types: constant references

final class cannot be subclassed

final method cannot be overridden or hidden by subclasses

final int number = 7; number = ...; //NO! number++; //NO!

final Robot R2D2 = new Robot(); R2D2 = ...; //NO!

R2D2.positionX = 15; //YES! R2D2.positionY = 20; //YES!

(23)

Exception handling

Allows to forward the exception handling in a

qualified context (at a higher level)

Simplifies the code through a recentralisation

of exception handling

Exceptions

triggered with the instruction throw

caught in a block try

(24)

Exception handling

If a method p() uses an instruction susceptible to trigger an

exception:

• catch and handle the exception

void p(){ ...

try { ... exception ...}

catch(xxxException e){//handling e} }

• or, propagate the exception

void p() throws xxxException{

... if(some test) throw new xxxException() ...}

finally{ ... } associated with a try{...} block,

(25)
(26)

Java standard exceptions

ex: NullPointerException, NumberFormatException, IndexOutOfBoundsException

(27)

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(n);

Handling:

try {…} catch (ExceptionRien e){

System.out.println(e.getMessage()); //ou

(28)

Inheritance

Based on "is-a" relationship

Subclass: more specialised

Superclass: more general

Subclass is derived or inherits from superclass hence, the terms 'derived class' and 'base class' respectively

extends keyword

Objects of a subclass

can be treated as objects of its superclass

(29)

java.lang.Object

The root of the class hierarchy:

every class has Object as a superclass

Provides a number of methods that are

common to all objects (including arrays):

clone()

equals(Object o)

hashCode()

finalize()

toString()

+ synchronisation methods

(30)

You can only inherit

from one class

(31)

Chaining constructors

When a class defines no constructor, the compiler will

automatically add one:

class MaClasse { MaClasse() { super(); } ... }

super() - calls the constructor of the superclass

All constructors (except those of java.lang.Object)

call another constructor:

a constructor of the superclass: super(...)

another constructor of the same class: this(...)

(32)

Virtual methods

A subclass can override (redefine) methods inherited from its superclass.

to specialise these methods to suit the new problem

NB: override <> overloading

New and old version must have the same prototype:

same return type

same argument types

Private, final methods cannot be overrode!

Private members are hidden from subclass

Objects of the subclass will work with the new version of the methods

Superclass’s methods of the same name can be reused by using the keyword super.methodName(...)

(33)

Polymorphism

"exist in many forms"

Object polymorphism: an object can be treated

in different ways

A Manager object can be seen as an Employee object

as well

Method polymorphism: calling a method

overrode for different objects which has

different behaviour according to the object type

Different objects interpret the same method differently: how do cats and dogs "talk"?

(34)

Object polymorphism:

Upcasting

Cast "up" the inheritance diagram

Take an object reference and treat it as if it refers to its base type

Cat c = new Cat("Tom"); Animal a = c; // upcasting

Cannot invoke methods not provided by the base type

a.chaseTail();

//Error! method not found in class Animal

But

a.makeASound();

//"Meow…", Cat's makeASound() gets to run

(35)

Object polymorphism:

Downcasting

Cast "down" the inheritance diagram

Animal animal = new Cat("Tom"); //upcast ...

Cat c = (Cat) animal; // downcast c.sayHello(); // "Meow.."

But, not always possible. Why?

Animal animal = new Animal("Dummy"); ...

Cat c = (Cat) animal; // run-time error

(36)

Method polymorphism

Animal pet1 = new Cat("tom"); Animal pet2 = new Cow("mini"); ...

pet1.makeASound(); pet2.makeASound();

The same message is interpreted differently

depending on the object's type:

(37)

Dynamic binding

Method binding: connect a method call to a

method body

Static/early binding: performed by compiler/linker before the program is run.

the only option of procedural languages.

Dynamic/late binding: performed at run-time

Java uses late binding, except for static, final, and private methods.

(38)

Generic programming

Write code that can be

reused

for

objects of many

different types

Indicate some type

parameters

instead of actual types

Java 1.5: generic classes and

methods

(39)

Generic classes

General form of a generic class:

class A<T1, T2, ...> {...} T1, T2, ... generic parameters

Example:

class Stack<T>{ //generic stack private int s;

private Object[] P = new Object[100]; public Stack() {s=-1;}

public void push(T e) {s++; P[s]=e}; ...

}

Student toto = new Student("toto",...);

Stack<Student> sStu = new Stack<Student>(); sStu.push(toto);

(40)

Generic methods

public <T> void inspect(T t) { System.out.println("T: " + t.getClass().getName()); } ... <String>inspect(String s); optional

References

Related documents

(B) the adsorption at a single site on the surface may involve multiple molecules at the same time.. (C) the mass of gas striking a given area of surface is proportional to the

The point at which the resultant of lift forces acts is: A) the hub. B) the center of gravity. D) the center of pressure.. A) airflow velocity increasing downward having been

Acutely exposed animals require calcium gluconate (IV) and oral magnesium hydroxide or milk to bind fluoride before absorption. In chronic exposure, control is difficult unless

To assure lasting compliance on recidivist properties, the Neighborhood Services Unit will initiate non-complaint based exterior inspections, code enforcement on designated

There are many augmented reality (AR) applications avail- able that can be used to create educational contents for these mobile devices. This paper surveys the most popular

If index futures is trading above 5099, we can buy index stocks in cash market and simultaneously sell index futures to lock the gains equivalent to the difference between

Judith Kates is Professor of Jewish Women's Studies at Hebrew College, currently teaching Bible and Jewish traditions of commentary for the new Rabbinical School

Changes in sensory attributes over time after harvest were observed and all 9:00hrs samples were rated highly for each attribute compared to the 12:00hrs and 15:00hrs samples