t
t
t
t
t t 4) Initialisation & nettoyage
tttt
4) Initialization & Cleanup
Texte original t Traducteur : F. DEFAIX et Y. CHICHA
t
t
    
Ce chapitre contient 6 pages
1 2 3 4 5 6
\\\
t t t
t t t
t
05.07.01 - version 1.5 [Armel] :
- Ajout des tags de séparation des pages pour le site.
25.04.2001 - version 1.4 [Armel] :
- Mise en forme du code html (titres-hx[verdana], paragraphes-p[Georgia], code-blockquote).
13.04.2001 - version 1.3 [Florence DEFAIX]
- Après corrections proposées par Jérome QUELIN et J-P VIDAL.
Traducteur :
- Florence DEFAIX & Y. CHICHA
Texte original :
-Thinking in Java, 2nd edition, Revision 10
© 2000 by Bruce Eckel
t t t
4: Initialization & Cleanup t 4: Initialisation & Nettoyage
t t t
As the computer revolution progresses, “unsafe” programming has become one of the major culprits that makes programming expensive. t Depuis le début de la révolution informatique, la programmation «sans garde-fou» est la principale cause des coûts de développement excessifs.
t t t
Two of these safety issues are initialization and cleanup. Many C bugs occur when the programmer forgets to initialize a variable. This is especially true with libraries when users don’t know how to initialize a library component, or even that they must. Cleanup is a special problem because it’s easy to forget about an element when you’re done with it, since it no longer concerns you. Thus, the resources used by that element are retained and you can easily end up running out of resources (most notably, memory). t L'initialisation et la libération d'éléments sont deux problèmes majeurs. De nombreux bogues en C surviennent lorsque le programmeur oublie d'initialiser une variable. L'utilisation de blibliothèques augmente ce risque car les utilisateurs ne savent pas toujours comment initialiser certains composants, ni même qu'ils le doivent. La phase de nettoyage ou libération pose problème dans la mesure où il est très facile d'oublier l'existence d'un élément dont on n'a plus besoin, car justement il ne nous intéresse plus. Dans ce cas, certaines ressources utilisées par un élément oublié sont conservées. Ce phénomène peut entraîner un manque de ressources (dans la majorité des cas, un manque de mémoire).
t t t
C++ introduced the concept of a constructor, a special method automatically called when an object is created. Java also adopted the constructor, and in addition has a garbage collector that automatically releases memory resources when they’re no longer being used. This chapter examines the issues of initialization and cleanup, and their support in Java. t C++ a introduit la notion de constructeur, une méthode appelée automatiquement à la création d'un objet. Java utilise aussi les constructeurs, associé à un ramasse-miettes qui libère les ressources mémoire lorsqu'elles ne sont plus utilisées. Ce chapitre décrit les concepts d'initialisation et de libération, ainsi que leur support dans Java.
t t t

Guaranteed initialization with the constructor

t

Garantie d'initialisation grâce au constructeur

t t t
You can imagine creating a method called initialize( ) for every class you write. The name is a hint that it should be called before using the object. Unfortunately, this means the user must remember to call the method. In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed. t Pour chaque classe il serait possible de créer une méthode initialise( ). Ce nom inciterait à exécuter la méthode avant d'utiliser l'objet. Malheureusement ce serait à l'utilisateur de se souvenir d'appeler cette méthode pour chaque instance. En Java, le concepteur d'une classe peut garantir son initialisation grâce à une méthode spéciale que l'on dénomme constructeur. Quand une classe possède un constructeur, Java l'appelle automatiquement à toute création d'objets, avant qu'ils ne puissent être utilisés. L'initialisation est donc bien garantie.
t t t
The next challenge is what to name this method. There are two issues. The first is that any name you use could clash with a name you might like to use as a member in the class. The second is that because the compiler is responsible for calling the constructor, it must always know which method to call. The C++ solution seems the easiest and most logical, so it’s also used in Java: the name of the constructor is the same as the name of the class. It makes sense that such a method will be called automatically on initialization. t Le premier problème consiste à trouver un nom pour cette méthode ce qui entraîne deux nouveaux problèmes. Tout d'abord il pourrait y avoir un conflit avec le nom d'un attribut. Ensuite c'est à la compilation que l'appel du constructeur est vérifié. Il faut donc que le compilateur puisse décider du nom du constructeur. La solution de C++ paraît la plus simple et la plus logique, elle est donc aussi utilisée en Java. Il faut donc donner au constructeur le nom de sa classe. Il semble naturel qu'une telle méthode soit en charge de l'initialisation de la classe.
t t t
Here’s a simple class with a constructor: t Voici une classe avec un constructeur :
t t t
//: c04:SimpleConstructor.java
// Demonstration of a simple constructor.

class Rock {
  Rock() { // This is the constructor
    System.out.println("Creating Rock");
  }
}

public class SimpleConstructor {
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new Rock();
  }
} ///:~
t
//: c04:SimpleConstrutor.java
// Démonstration d'un constructeur.

class Rock {
  Rock() { // Ceci est un constructeur
    System.out.println("Creating Rock");
  }
}

public class SimpleConstructor {
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new Rock();
  }
} ///:~
t t t
Now, when an object is created: t Quand un objet est créé :
t t t
new Rock();
t
new Rock();
t t t
storage is allocated and the constructor
is called. It is guaranteed that the object will be properly initialized before
you can get your hands on it.
t de l'espace mémoire est alloué et le constructeur est appelé. L'objet sera obligatoirement initialisé avant qu'il ne puisse être manipulé.
t t t
Note that the coding style of making the
first letter of all methods lowercase does not apply to constructors, since the
name of the constructor must match the name of the class
exactly.
t Notez que la convention de nommage qui impose une minuscule pour la première lettre des noms de méthode ne s'applique pas aux constructeurs, leur nom devant exactement coïncider avec celui de la classe.
t t t
Like any method, the constructor can have
arguments to allow you to specify
how an object is created. The above example can easily be changed so the
constructor takes an argument:

t Comme les autres méthodes, un constructeur peut prendre des paramètres. Cela permet de préciser comment l'objet va être créé. Notre premier exemple peut facilement être modifié pour que le constructeur prenne un unique paramètre :
t t t
//: c04:SimpleConstructor2.java
// Constructors can have arguments.

class Rock2 {
  Rock2(int i) {
    System.out.println(
      "Creating Rock number " + i);
  }
}

public class SimpleConstructor2 {
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new Rock2(i);
  }
} ///:~
t
//: c04:SimpleConstructor2.java
// Les constructeurs peuvent prendre des paramètres.

class Rock2 {
  Rock2(int i) {
    System.out.println(
      "Creating Rock number " + i);
  }
}

public class SimpleConstructor2 {
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new Rock2(i);
  }
} ///:~
t t t
Constructor arguments provide you with a way to provide parameters for the initialization of an object. For example, if the class Tree has a constructor that takes a single integer argument denoting the height of the tree, you would create a Tree object like this: t Les paramètres des constructeurs permettent de personnaliser la création des objets. Par exemple, si la classe Tree (arbre) a un constructeur avec un paramètre de type int qui détermine la hauteur de l'arbre, un objet Tree se crée de la façon suivante :
t t t
Tree t = new Tree(12);  // 12-foot tree
t
Tree t = new Tree(12);  // arbre de 12 pieds
t t t
If Tree(int) is your only
constructor, then the compiler won’t let you create a Tree object
any other way.
t De plus, si Tree(int) est le seul constructeur, le compilateur ne permettra pas de créer un objet Tree d'une autre façon.
t t t
Constructors eliminate a large class of
problems and make the code easier to read. In the preceding code fragment, for
example, you don’t see an explicit call to some initialize( )
method that is conceptually separate from definition. In Java, definition and
initialization are unified concepts—you can’t have one without the
other.
t La notion de constructeur élimine toute une catégorie d'erreurs et rend plus aisée la lecture du code. Dans le fragment de code précédent, par exemple, il n'y a pas d'appel explicite à une certaine méthode initialise( ) qui serait conceptuellement séparée de la définition. En Java, definition et initialisation sont des concepts unifiés - il est impossible d'avoir l'un sans l'autre.
t t t
The constructor is an unusual type of
method because it has no return
value. This is distinctly
different from a void return value, in which the method returns nothing
but you still have the option to make it return something else. Constructors
return nothing and you don’t have an option. If there was a return value,
and if you could select your own, the compiler would somehow need to know what
to do with that return
value.
t Un constructeur est une méthode très spéciale de par le fait qu'elle n'a pas de valeur de retour. Cela n'a absolument rien à voir avec le type de retour void, qui signifie qu'une méthode ne renvoie rien mais qu'il aurait tout à fait été possible de lui faire renvoyer autre chose. Les constructeurs ne retournent rien et on n'a pas le choix. S'il y avait une valeur de retour, et si l'on pouvait choisir son type, le compilateur devrait trouver une utilisation à cette valeur.
t t t


Method overloading


t

Surcharge de méthodes

t t t
One of the important features in any
programming language is the use of names. When you create an object, you give a
name to a region of storage. A method is a name for an action. By using names to
describe your system, you create a program that is easier for people to
understand and change. It’s a lot like writing prose—the goal is to
communicate with your readers.
t L'un des points les plus importants de tout langage de programmation est le nommage. Créer un objet revient à donner un nom à un emplacement mémoire. Une méthode est un nom d'action. En utilisant des noms pour décrire un système, on simplifie la lecture et la modification des programmes. Cela s'apparente à l'écriture en prose dont le but est de communiquer avec le lecteur.
t t t
You refer to all objects and methods by
using names. Well-chosen names make it easier for you and others to understand
your code.
t On se réfère à tous les objets et méthodes en utilisant leurs noms. Des noms biens choisis rendent la compréhension du code plus aisée, tant pour le développeur que pour les relecteurs.
t t t
A problem arises when mapping the concept
of nuance in human language onto a programming language. Often, the same word
expresses a number of different meanings—it’s overloaded.
This is useful, especially when it comes to trivial differences. You say
“wash the shirt,” “wash the car,” and “wash the
dog.” It would be silly to be forced to say, “shirtWash the
shirt,” “carWash the car,” and “dogWash the dog”
just so the listener doesn’t need to make any distinction about the action
performed. Most human languages are redundant, so even if you miss a few words,
you can still determine the meaning. We don’t need unique
identifiers—we can deduce meaning from context.
t Les difficultés commencent lorsque l'on essaie d'exprimer les nuances subtiles du langage humain dans un langage de programmation. Très souvent, un même mot a plusieurs sens, on parle de surcharge. Cette notion est très pratique pour exprimer les différences triviales de sens. On dit « laver la chemise » ,  « laver la voiture »  et  « laver le chien » . Cela paraîtrait absurde d'être obligé de dire « laverChemise la chemise » ,  « laverVoiture la voiture »  et  « laverChien le chien »  pour que l'auditoire puisse faire la distinction entre ces actions. La plupart des langages humains sont redondants à tel point que même sans entendre tous les mots, il est toujours possible de comprendre le sens d'une phrase. Nous n'avons aucunement besoin d'identifiants uniques, le sens peut être déduit du contexte.
t t t
Most programming languages (C in
particular) require you to have a unique identifier for each function. So you
could not have one function called print( ) for printing integers
and another called print( ) for printing floats—each function
requires a unique name.
t La plupart des langages de programation (C en particulier) imposent un nom unique pour chaque fonction. Ils ne permettent pas d'appeler une fonction affiche( ) pour afficher des entiers et une autre appelée affiche( ) pour afficher des flottants, chaque fonction doit avoir un nom unique.
t t t
In Java (and C++), another factor forces
the overloading of method names: the
constructor. Because the
constructor’s name is predetermined by the name of the class, there can be
only one constructor name. But what if you want to create an object in more than
one way? For example, suppose you build a class that can initialize itself in a
standard way or by reading information from a file. You need two constructors,
one that takes no arguments (the default constructor, also called the
no-arg constructor), and one that takes a String as an argument,
which is the name of the file from which to initialize the object. Both are
constructors, so they must have the same name—the name of the class. Thus,
method overloading is essential to allow the same method name to be used
with different argument types. And although method overloading is a must for
constructors, it’s a general convenience and can be used with any method.

t En Java (et en C++), un autre facteur impose la surcharge de noms de méthodes : les constructeurs. Comme le nom d'un constructeur est déterminé par le nom de la classe, il ne peut y avoir qu'un seul nom de constructeur. Mais que se passe-t-il quand on veut créer un objet de différentes façons ? Par exemple, supposons que l'on construise une classe qui peut s'initialiser de façon standard ou en lisant des informations depuis un fichier. Nous avons alors besoin de deux constructeurs, l'un ne prenant pas de paramètre ( le constructeur par défaut, aussi appelé le constructeur sans paramètre / no-arg ), et un autre prenant une Chaîne / String comme paramètre, qui représente le nom du fichier depuis lequel on souhaite initialiser l'objet. Tous les deux sont des constructeurs, ils doivent donc avoir le même nom, le nom de la classe. Cela montre que la surcharge de méthode est essentielle pour utiliser le même nom de méthode pour des utilisations sur différents types de paramètres. Et si la surcharge de méthode est obligatoire pour les constructeurs, elle est aussi très pratique pour les méthodes ordinaires.
t t t
Here’s an example that shows both
overloaded constructors and overloaded ordinary methods:

t L'exemple suivant montre à la fois une surcharge de constructeur et une surcharge de méthode ordinaire :
t t t
//: c04:Overloading.java
// Demonstration of both constructor
// and ordinary method overloading.
import java.util.*;

class Tree {
  int height;
  Tree() {
    prt("Planting a seedling");
    height = 0;
  }
  Tree(int i) {
    prt("Creating new Tree that is "
        + i + " feet tall");
    height = i;
  }
  void info() {
    prt("Tree is " + height
        + " feet tall");
  }
  void info(String s) {
    prt(s + ": Tree is "
        + height + " feet tall");
  }
  static void prt(String s) {
    System.out.println(s);
  }
}

public class Overloading {
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++) {
      Tree t = new Tree(i);
      t.info();
      t.info("overloaded method");
    }
    // Overloaded constructor:
    new Tree();
  }
} ///:~
t
//: c04:Overloading.java
// Exemple de surcharge de constructeur
// et de méthode ordinaire.
import java.util.*;

class Tree {
  int height;
  Tree() {
    prt("Planting a seedling");  // Planter une jeune pousse
    height = 0;
  }
  Tree(int i) {
    prt("Creating new Tree that is " // Création d'un Arbre
        + i + " feet tall"); // de i pieds de haut
    height = i;
  }
  void info() {
    prt("Tree is " + height // L'arbre mesure x pieds
        + " feet tall");
  }
  void info(String s) {
    prt(s + ": Tree is "      // valeur de s :  L'arbre mesure x pieds
        + height + " feet tall");
  }
  static void prt(String s) {
    System.out.println(s);
  }
}

public class Overloading {
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++) {
      Tree t = new Tree(i);
      t.info();
      t.info("overloaded method");
    }
    // constructeur surchargé :
    new Tree();
  }
} ///:~
t t t
A Tree object can be created either as a seedling, with no argument, or as a plant grown in a nursery, with an existing height. To support this, there are two constructors, one that takes no arguments (we call constructors that take no arguments default constructors[27]) and one that takes the existing height. t Un objet Tree peut être créé soit en tant que jeune pousse, sans fournir de paramètre, soit en tant que plante poussée en pépinière, en donnant une hauteur initiale. Pour permettre ceci, il y a deux constructeurs, l'un ne prend pas de paramètre (on appelle les constructeurs sans paramètre des constructeurs par défaut name="fnB27">[27]) et un deuxième qui prend la hauteur initiale de l'arbre.
t t t
You might also want to call the info( ) method in more than one way. For example, with a String argument if you have an extra message you want printed, and without if you have nothing more to say. It would seem strange to give two separate names to what is obviously the same concept. Fortunately, method overloading allows you to use the same name for both. t Il est aussi possible d'appeler la méthode info( ) de plusieurs façons. Par exemple, avec un paramètre String si un message supplémentaire est désiré, ou sans paramètre lorsqu'il n'y a rien d'autre à dire. Cela paraîtrait étrange de donner deux noms distincts à ce qui est manifestement le même concept. Heureusement, la surchage de méthode permet l'utilisation du même nom pour les deux.
t t t

Distinguishing overloaded methods

t

Différencier les méthodes surchargées

t t t
If the methods have the same name, how can Java know which method you mean? There’s a simple rule: each overloaded method must take a unique list of argument types. t Quand deux méthodes ont le même nom, comment Java peut-il décider quelle méthode est demandée ? Il y a une règle toute simple : chaque méthode surchargée doit prendre une liste unique de types de paramètres.
t t t
If you think about this for a second, it makes sense: how else could a programmer tell the difference between two methods that have the same name, other than by the types of their arguments? t Lorsqu'on y pense, cela paraît tout à fait sensé : comment le développeur lui-même pourrait-il choisir entre deux méthodes du même nom, autrement que par le type des paramètres ?
t t t
Even differences in the ordering of arguments are sufficient to distinguish two methods: (Although you don’t normally want to take this approach, as it produces difficult-to-maintain code.) t Une différence dans l'ordre des paramètres est suffisante pour distinguer deux méthodes ( cette approche n'est généralement pas utilisée car elle donne du code difficile à maintenir.) :
t t t
//: c04:OverloadingOrder.java
// Overloading based on the order of
// the arguments.

public class OverloadingOrder {
  static void print(String s, int i) {
    System.out.println(
      "String: " + s +
      ", int: " + i);
  }
  static void print(int i, String s) {
    System.out.println(
      "int: " + i +
      ", String: " + s);
  }
  public static void main(String[] args) {
    print("String first", 11);
    print(99, "Int first");
  }
} ///:~
t
//: c04:OverloadingOrder.java
// Surcharge basée sur l'ordre
// des paramètres.

public class OverloadingOrder {
  static void print(String s, int i) {
    System.out.println(
      "String: " + s +
      ", int: " + i);
  }
  static void print(int i, String s) {
    System.out.println(
      "int: " + i +
      ", String: " + s);
  }
  public static void main(String[] args) {
    print("String first", 11);
    print(99, "Int first");
  }
} ///:~
t t t
The two print( ) methods have identical arguments, but the order is different, and that’s what makes them distinct. t Les deux méthodes print( ) ont les mêmes paramètres, mais dans un ordre différent, et c'est ce qui les différencie.
t t t

Overloading with primitives

t

Surcharge avec types de base

t t t
A primitive can be automatically promoted from a smaller type to a larger one and this can be slightly confusing in combination with overloading. The following example demonstrates what happens when a primitive is handed to an overloaded method: t Un type de base peut être promu automatiquement depuis un type plus petit vers un plus grand ; ceci peut devenir déconcertant dans certains cas de surcharge. L'exemple suivant montre ce qui se passe lorsqu'un type de base est passé à une méthode surchargée :
t t t
//: c04:PrimitiveOverloading.java
// Promotion of primitives and overloading.

public class PrimitiveOverloading {
  // boolean can't be automatically converted
  static void prt(String s) {
    System.out.println(s);
  }

  void f1(char x) { prt("f1(char)"); }
  void f1(byte x) { prt("f1(byte)"); }
  void f1(short x) { prt("f1(short)"); }
  void f1(int x) { prt("f1(int)"); }
  void f1(long x) { prt("f1(long)"); }
  void f1(float x) { prt("f1(float)"); }
  void f1(double x) { prt("f1(double)"); }

  void f2(byte x) { prt("f2(byte)"); }
  void f2(short x) { prt("f2(short)"); }
  void f2(int x) { prt("f2(int)"); }
  void f2(long x) { prt("f2(long)"); }
  void f2(float x) { prt("f2(float)"); }
  void f2(double x) { prt("f2(double)"); }

  void f3(short x) { prt("f3(short)"); }
  void f3(int x) { prt("f3(int)"); }
  void f3(long x) { prt("f3(long)"); }
  void f3(float x) { prt("f3(float)"); }
  void f3(double x) { prt("f3(double)"); }

  void f4(int x) { prt("f4(int)"); }
  void f4(long x) { prt("f4(long)"); }
  void f4(float x) { prt("f4(float)"); }
  void f4(double x) { prt("f4(double)"); }

  void f5(long x) { prt("f5(long)"); }
  void f5(float x) { prt("f5(float)"); }
  void f5(double x) { prt("f5(double)"); }

  void f6(float x) { prt("f6(float)"); }
  void f6(double x) { prt("f6(double)"); }

  void f7(double x) { prt("f7(double)"); }

  void testConstVal() {
    prt("Testing with 5");
    f1(5);f2(5);f3(5);f4(5);f5(5);f6(5);f7(5);
  }
  void testChar() {
    char x = 'x';
    prt("char argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testByte() {
    byte x = 0;
    prt("byte argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testShort() {
    short x = 0;
    prt("short argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testInt() {
    int x = 0;
    prt("int argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testLong() {
    long x = 0;
    prt("long argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testFloat() {
    float x = 0;
    prt("float argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testDouble() {
    double x = 0;
    prt("double argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  public static void main(String[] args) {
    PrimitiveOverloading p =
      new PrimitiveOverloading();
    p.testConstVal();
    p.testChar();
    p.testByte();
    p.testShort();
    p.testInt();
    p.testLong();
    p.testFloat();
    p.testDouble();
  }
} ///:~
t
//: c04:PrimitiveOverloading.java
// Promotion des types de base et surcharge.

public class PrimitiveOverloading {
  // boolean ne peut pas être converti automatiquement
  static void prt(String s) {
    System.out.println(s);
  }

  void f1(char x) { prt("f1(char)"); }
  void f1(byte x) { prt("f1(byte)"); }
  void f1(short x) { prt("f1(short)"); }
  void f1(int x) { prt("f1(int)"); }
  void f1(long x) { prt("f1(long)"); }
  void f1(float x) { prt("f1(float)"); }
  void f1(double x) { prt("f1(double)"); }

  void f2(byte x) { prt("f2(byte)"); }
  void f2(short x) { prt("f2(short)"); }
  void f2(int x) { prt("f2(int)"); }
  void f2(long x) { prt("f2(long)"); }
  void f2(float x) { prt("f2(float)"); }
  void f2(double x) { prt("f2(double)"); }

  void f3(short x) { prt("f3(short)"); }
  void f3(int x) { prt("f3(int)"); }
  void f3(long x) { prt("f3(long)"); }
  void f3(float x) { prt("f3(float)"); }
  void f3(double x) { prt("f3(double)"); }

  void f4(int x) { prt("f4(int)"); }
  void f4(long x) { prt("f4(long)"); }
  void f4(float x) { prt("f4(float)"); }
  void f4(double x) { prt("f4(double)"); }

  void f5(long x) { prt("f5(long)"); }
  void f5(float x) { prt("f5(float)"); }
  void f5(double x) { prt("f5(double)"); }

  void f6(float x) { prt("f6(float)"); }
  void f6(double x) { prt("f6(double)"); }

  void f7(double x) { prt("f7(double)"); }

  void testConstVal() {
    prt("Testing with 5");
    f1(5);f2(5);f3(5);f4(5);f5(5);f6(5);f7(5);
  }
  void testChar() {
    char x = 'x';
    prt("char argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testByte() {
    byte x = 0;
    prt("byte argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testShort() {
    short x = 0;
    prt("short argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testInt() {
    int x = 0;
    prt("int argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testLong() {
    long x = 0;
    prt("long argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testFloat() {
    float x = 0;
    prt("float argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  void testDouble() {
    double x = 0;
    prt("double argument:");
    f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);
  }
  public static void main(String[] args) {
    PrimitiveOverloading p =
      new PrimitiveOverloading();
    p.testConstVal();
    p.testChar();
    p.testByte();
    p.testShort();
    p.testInt();
    p.testLong();
    p.testFloat();
    p.testDouble();
  }
} ///:~
t t t
If you view the output of this program, you’ll see that the constant value 5 is treated as an int, so if an overloaded method is available that takes an int it is used. In all other cases, if you have a data type that is smaller than the argument in the method, that data type is promoted. char produces a slightly different effect, since if it doesn’t find an exact char match, it is promoted to int. t En regardant la sortie du programme, on voit que la constante 5 est considérée comme un int. Lorsqu'une méthode surchargée utilisant un int est disponible, elle est utilisée. Dans tous les autres cas, si un type de données est plus petit que l'argument de la méthode, le type est promu. char est légèrerent différent, comme il ne trouve pas une correspondance exacte, il est promu vers un int.
t t t
t t t
t t
    
///
t t t
t
     
Sommaire Le site de Bruce Eckel