licence mention informatique – l2/s4 – 2011 programmation...

Post on 06-Mar-2018

221 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Licence Mention Informatique – L2/S4 – 2011Programmation Object

&Genie Logiciel

Burkhart WolffDépartement Informatique

2011 B. Wolff, L2-PO&GL, Inheritance etc 2

Mise en œuvre associée

C1 - 28.1, 11:15 - 13:00, [336-109]: Compléments de Programmation Java

C2 - 4.2, 11:15 - 13:00, [336-109]: Compléments sur héritage et redéfinition: covariance/contravariance, redéfinition vs surcharge, héritage vs composition etc.

C3 - 11.2, 11:15 - 13:00, [336-109]: Déclaration et gestion des exceptions

C4 - 18.2, 11:15 - 13:00, [336-109]: Polymorphisme en Java

C5 - 4.3, 11:15 - 13:00, [336-109]: Introduction aux "Patrons de conception" (en TD principalement via des exemples stéréotypes) Introduction Genie LogicielCycle de vie du logiciel et documents associés

C6 - 11.3, 11:15 - 13:00, [336-109]: Introduction à UML

C7 - 25.3, 11:15 - 13:00, [336-109]: UML: diagramme de cas d'utilisation, diagrammes de classes, notions d'invariants.

C8 - 1.4, 11:15 - 13:00, [336-109]: Diagrammes de séquence en analyse. Notion de scenario.

C9 - 8.4., 11:15 - 13:00, [336-109]: Introduction aux machines à états.

Partiel: 18.3.2011 (á confirmer) Examen: 27.5.2011 (á confirmer)

2011 B. Wolff, L2-PO&GL, Inheritance etc 3

Overview

Why Inheritance : Taming the Similarity on Data

Inheritance inheritance „classic“, with recursion and super. inheritance : overriding vs. hiding. inheritance : overriding vs. overloading (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation abstract classes and abstract methods

2011 B. Wolff, L2-PO&GL, Inheritance etc 4

Overview

Why Inheritance : Taming the Similarity on Data

Inheritance inheritance „classic“, with recursion and super. inheritance : overriding vs. hiding. inheritance : overriding vs. overloading (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation abstract classes and abstract methods

2011 B. Wolff, L2-PO&GL, Inheritance etc 5

Why Inheritance ?

Motivation Different kinds of objects often have a certain amount in common with each other. This is reflected by a certain number of common fields (with same type). On the other hands, objects will have data that is specific to their kind (=class)

2011 B. Wolff, L2-PO&GL, Inheritance etc 6

Why Inheritance ?

Examples: Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Gui-elements (Widgets), Cars, Aircrafts ...

2011 B. Wolff, L2-PO&GL, Inheritance etc 7

Why Inheritance ?

Motivation Other (old) idea (ADT 72 !): consider the operationstogether with the data they operate on !Data should be ONLY manipulated by the operationson them ( ⟹ classes are a means to

encapsulation and data abstraction)

Consequence: there must be ways to reuse general definitions of objects to special cases (this is what inheritance does

for you !) distinguishing special behaviour from general one!

2011 B. Wolff, L2-PO&GL, Inheritance etc 8

Overview

Why Inheritance : Taming the Similarity on Data

Inheritance inheritance „classic“, with recursion and super. inheritance : overriding vs. hiding. inheritance : overriding vs. overloading (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation abstract classes and abstract methods

2011 B. Wolff, L2-PO&GL, Inheritance etc 9

Class Declarations (R)

Class Declarations Revisited

Syntax : class <class-name> { // field, constructor,

// and method declarations}class <class-name> extends <sup-class-name>

// field, constructor, // and method declarations}

Note: So - method declarations are always in the context of a class-declaration. Therefore, there is usually anobject to which the method refers to.(Exceptions are, eg., Systems.out.println ...)

2011 B. Wolff, L2-PO&GL, Inheritance etc 10

Class Declarations (R)

Class Declarations Revisited

Syntax : class <class-name> { // field, constructor,

// and method declarations}class <class-name> extends <sup-class-name>

// field, <modifier><type><methodname>(<arg-list>)

{ … this … }}

Note: The method-body of a declaration inside a class may containa special parameter, called this, having the static type of the surrounding class, which refers to the “first argument”of a method call (the thing before the dot ...)

2011 B. Wolff, L2-PO&GL, Inheritance etc 11

Overriding vs Hiding(1)

Method - calls (“invocation”) for non-constructors:

Syntax : <expr>.<methodname>(<expr-list>)

Thus: a.f(b) is in principle f(a,b)

(where a is bound to the implicit argument this)

BUT it is more than that: it's dynamic (actual) type is used to distinguish what method is actually called (late binding, dynamic binding) in case that several methods fit … due to overriding, hiding and overloading invocations.

2011 B. Wolff, L2-PO&GL, Inheritance etc 12

Methods and „this“ (1)

Method - calls (“invocation”):For example, the Point class was written like this

public class Point { public int x = 0; public int y = 0;

//constructor public Point(int x, int y) {

this.x = x;this.y = y;

}}

2011 B. Wolff, L2-PO&GL, Inheritance etc 13

Methods and „this“ (2)

Method - calls (“invocation”):… or shorter:

public class Point { public int x = 0; public int y = 0;

//constructor public Point(int a, int b) {

x = a;y = b;

}

}

Note: Methods having the same name as their (surrounding)class are called constructors.

2011 B. Wolff, L2-PO&GL, Inheritance etc 14

Methods and „this“ (3)

Example: Method - calls (“invocation”):

class CL { int x = 1; CL add () {x++; return this;}

}

public class thiss { public static void main(String[] args) { CL cl = new CL(); System.out.println( cl.x ); System.out.println( cl.add().x ); // 2 System.out.println( cl.add().add().x ); // 3

}}

2011 B. Wolff, L2-PO&GL, Inheritance etc 15

Methods and „this“ (4)

Example: Method - calls can be recursive (a bit artificial):

class CL { int x = 1; CL fac (int a) { if (a>0) x = a * fac(a-1).x;

return (this); }

}

public class thiss { public static void main(String[] args) { CL cl = new CL(); System.out.println( cl.fac(3).x ); // 6

}}

2011 B. Wolff, L2-PO&GL, Inheritance etc 16

Using Super (1)

Example

class Parent {  public Parent() {} }

class Child1 extends Parent {  public Child1() {    super();   } }

class Child2 extends Parent {  public Child2() {    super();  }

2011 B. Wolff, L2-PO&GL, Inheritance etc 17

Using Super (2)

Example (ctd):

class Grandson extends Child2 {  public Grandson() {    super();  } } public class MainClass {  public static void main(String[] a) {    Child1 child = new Child1();    if (child instanceof Parent) {      System.out.println("true");    } }  }

Running this program yields what ?

2011 B. Wolff, L2-PO&GL, Inheritance etc 18

Using Super (3)

Example (ctd):

class Grandson extends Child2 {  public Grandson() {    super();  }

public class MainClass {  public static void main(String[] a) {    Child1 child = new Child1();    if (child instanceof Parent) {      System.out.println("true");    }

  }

Running this program yields what ? true.

2011 B. Wolff, L2-PO&GL, Inheritance etc 19

Overview

Why Inheritance : Taming the Similarity on Data

Inheritance inheritance „classic“, with recursion and super. inheritance : overriding vs. hiding. inheritance : overriding vs. overloading (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation abstract classes and abstract methods

2011 B. Wolff, L2-PO&GL, Inheritance etc 20

Overriding vs Hiding(1)

Method - declarations: Overriding.

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

2011 B. Wolff, L2-PO&GL, Inheritance etc 21

Overriding vs Hiding(2)

Method - declarations: Hiding.

If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.

Note: An instance method is a method which is associated with one object and may use the instance variables of that object. The opposite of an instance method is a static method.

The default for a method is to be an instance method.

2011 B. Wolff, L2-PO&GL, Inheritance etc 22

Overriding vs Hiding(3)

Example: public class Animal { public static void testClassMethod() { System.out.println("CM Animal."); } public void testInstanceMethod() { System.out.println("IM Animal."); } }

2011 B. Wolff, L2-PO&GL, Inheritance etc 23

Overriding vs Hiding(4)

Example:

public class Cat extends Animal { public static void testClassMethod() { System.out.println("CM Cat."); } public void testInstanceMethod() { System.out.println("IM Cat."); }

...}

2011 B. Wolff, L2-PO&GL, Inheritance etc 24

Overriding vs Hiding(5)

Example:

public class Cat extends Animal { ...

public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); Cat.testClassMethod(); myCat.testInstanceMethod(); myAnimal.testInstanceMethod(); }}

2011 B. Wolff, L2-PO&GL, Inheritance etc 25

Overriding vs Hiding(6)

Example:

public class Cat extends Animal { ...

public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); ??? Cat.testClassMethod(); ??? myCat.testInstanceMethod(); ??? myAnimal.testInstanceMethod(); ??? }}

2011 B. Wolff, L2-PO&GL, Inheritance etc 26

Overriding vs Hiding(7)

Example:

public class Cat extends Animal { ...

public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); “CM Animal” Cat.testClassMethod(); “CM Cat” myCat.testInstanceMethod(); “IM Cat” myAnimal.testInstanceMethod(); “IM Cat” }}

2011 B. Wolff, L2-PO&GL, Inheritance etc 27

Overriding vs Hiding(8)

All objects inherit from class Object the methods

toString() : string representation of object hasCode() : representation of an object by a (hash) key

(different when copying due to internal unique id)

clone() : copy of an objet equals() : test of equality of two objects

Inheritage, Overriding, Hiding and Overloading enable a flixible way to adapt this „Object-Infrastructure“ to ones needs ...

2011 B. Wolff, L2-PO&GL, Inheritance etc 28

Overriding vs Hiding(9)

Practical example: Overriding .equal !

Problem: a == b

is the referential equality, i.e.it is a test if two references (adresses in the memory)

Solution : override .equals !!! (similarly: override toString)

2011 B. Wolff, L2-PO&GL, Inheritance etc 29

Overriding vs Hiding(10)

Solution : override .equals !!! (similarly: override toString) public boolean equals(Object o) allows for problem-specific comparisons. Default : reference equality Overriding can allows to compare values of a class In principle can compare objects of different types In practice: always casting along the following scheme:

public boolean equals(Object o) { if (!(o instanceof MonObjet)) { return false;} MonObjet mo = (MonObjet) o; // comparaison }G.

2011 B. Wolff, L2-PO&GL, Inheritance etc 30

Overriding vs Hiding(11)

Example:

public class MyString { private String s; public MyString(String s) { this.s = s; }

public static void main(String[] a) { MyString s1 = new MyString("bonjour"); MyString s2 = new MyString("bonjour"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); }}

) affiche deux fois false

G.G.

2011 B. Wolff, L2-PO&GL, Inheritance etc 31

Overriding vs Hiding(12)

Example:

public class MyString1 { private String s; public MyString1(String s) { this.s = s; }

public boolean equals(Object o) { if (!(o instanceof MyString1)){return false;} MyString1 mo = (MyString1) o; return mo.s.equals(this.s); }

...

2011 B. Wolff, L2-PO&GL, Inheritance etc 32

Overriding vs Hiding(13)

Example (ctd):

... public static void main(String[] a) { MyString1 s1 = new MyString1("bonjour"); MyString1 s2 = new MyString1("bonjour"); System.out.println(s1.equals(s2)); } }

2011 B. Wolff, L2-PO&GL, Inheritance etc 33

Overview

Why Inheritance : Taming the Similarity on Data

Inheritance inheritance „classic“, with recursion and super. inheritance : overriding vs. hiding. inheritance : overriding vs. overloading (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation abstract classes and abstract methods

2011 B. Wolff, L2-PO&GL, Inheritance etc 34

Overriding vs Overloading (1)

Method - declarations: Overriding.

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

2011 B. Wolff, L2-PO&GL, Inheritance etc 35

Overriding vs Overloading (2)

Method - declarations: Overloading.

An instance method in a subclass with same name but different signature (plus the number and the type of its parameters) and return type as an instancemethod in the superclass overrides the superclass'smethod.

2011 B. Wolff, L2-PO&GL, Inheritance etc 36

Overriding vs Overloading (3)

Method - declarations: Overloading.

Already observed form of overloading:

s + i (where s::string and i::int) i + s

Another application is an equality between different types (but a finite, fixed number of signatures …)

s.equal(i) etc ...

2011 B. Wolff, L2-PO&GL, Inheritance etc 37

Overriding vs Overloading (4)

Example

public class Rectangle { private int x, y; private int width, height;

public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ...}

2011 B. Wolff, L2-PO&GL, Inheritance etc 38

A Note On Static Fields in Objects

Until now, all fields (“attributes”) in class declarations were dynamic, i.e. when calling a constructor, an object is created with its own fields in the memory.

Now, we introduce global variables that all instances have in common: class <class-name> [extends <sup-class-name>] . . .

<modifier> static <type><var> [= <expr>]. . .}

2011 B. Wolff, L2-PO&GL, Inheritance etc 39

A Note On Static Fields in Objects

Example: . . .

public class Etudiant { public static int n; public int id; private String nom;

public Etudiant(String nom) { this.nom = nom; this.id = n; Etudiant.n += 1; }

2011 B. Wolff, L2-PO&GL, Inheritance etc 40

A Note On Static Fields in Objects

Example:

. . .

public static void main(String[] n) { Etudiant e1 = new Etudiant("1"); Etudiant e2 = new Etudiant("2"); Etudiant e3 = new Etudiant("3"); System.out.println(e2.n); System.out.println(e2.id); }}

2011 B. Wolff, L2-PO&GL, Inheritance etc 41

A Note On Static Fields in Objects

Example:

. . .

public static void main(String[] n) { Etudiant e1 = new Etudiant("1"); Etudiant e2 = new Etudiant("2"); Etudiant e3 = new Etudiant("3"); System.out.println(e2.n); ? ? ? System.out.println(e2.id); ? ? ? }}

2011 B. Wolff, L2-PO&GL, Inheritance etc 42

Overview

Why Inheritance : Taming the Similarity on Data

Inheritance inheritance „classic“, with recursion and super. inheritance : overriding vs. hiding. inheritance : overriding vs. overloading (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation abstract classes and abstract methods

2011 B. Wolff, L2-PO&GL, Inheritance etc 43

Abstract Classes & Methods

Inheritance & Encapsulation:

Abstract Classes are a kind of Interface, that can be partially implemented. It can contain :

field declarations method declarations abstract method declarations (just a signature that

has to be overridden

later . . .

2011 B. Wolff, L2-PO&GL, Inheritance etc 44

Abstract Classes & Methods

Syntax:

abstract class <class-name> [extends<sup-class-name>]{

// field declarations . . . // non-abstract method declarations

<modifier> abstract <type><method>(<args>) ;

. . .

}

2011 B. Wolff, L2-PO&GL, Inheritance etc 45

Abstract Classes & Methods

Example:

public abstract class GraphicObject { // . . .

abstract void draw();

}

Now, in each of the subclasses Rectangle, Line, … the method draw has to be overridden in order to form a COMPLETE implementation.

2011 B. Wolff, L2-PO&GL, Inheritance etc 46

Overview

Why Inheritance : Taming the Similarity on Data ✔

Inheritance

inheritance „classic“, with recursion and super. ✔

inheritance : overriding vs. hiding. ✔

inheritance : overriding vs. overloading ✔ (+ „A Note On Static Fields in Objects“)

Inheritance and Encapsulation

abstract classes and abstract methods ✔

top related