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
t t t

Exercises

t

Exercices

t t t
Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from www.BruceEckel.com. t Les solutions aux exercices choisis peuvent être trouvées dans le document électronique The Thinking in Java Annotated Solution Guide, disponible pour une modeste somme à l'adresse www.BruceEckel.com.
t t t
  1. Create a class with a default constructor (one that takes no arguments) that prints a message. Create an object of this class.
  2. Add an overloaded constructor to Exercise 1 that takes a String argument and prints it along with your message.
  3. Create an array of object references of the class you created in Exercise 2, but don’t actually create objects to assign into the array. When you run the program, notice whether the initialization messages from the constructor calls are printed.
  4. Complete Exercise 3 by creating objects to attach to the array of references.
  5. Create an array of String objects and assign a string to each element. Print the array using a for loop.
  6. Create a class called Dog with an overloaded bark( ) method. This method should be overloaded based on various primitive data types, and print different types of barking, howling, etc., depending on which overloaded version is called. Write a main( ) that calls all the different versions.
  7. Modify Exercise 6 so that two of the overloaded methods have two arguments (of two different types), but in reversed order relative to each other. Verify that this works.
  8. Create a class without a constructor, and then create an object of that class in main( ) to verify that the default constructor is automatically synthesized.
  9. Create a class with two methods. Within the first method, call the second method twice: the first time without using this, and the second time using this.
  10. Create a class with two (overloaded) constructors. Using this, call the second constructor inside the first one.
  11. Create a class with a finalize( ) method that prints a message. In main( ), create an object of your class. Explain the behavior of your program.
  12. Modify Exercise 11 so that your finalize( ) will always be called.
  13. Create a class called Tank that can be filled and emptied, and has a death condition that it must be empty when the object is cleaned up. Write a finalize( ) that verifies this death condition. In main( ), test the possible scenarios that can occur when your Tank is used.
  14. Create a class containing an int and a char that are not initialized, and print their values to verify that Java performs default initialization.
  15. Create a class containing an uninitialized String reference. Demonstrate that this reference is initialized by Java to null.
  16. Create a class with a String field that is initialized at the point of definition, and another one that is initialized by the constructor. What is the difference between the two approaches?
  17. Create a class with a static String field that is initialized at the point of definition, and another one that is initialized by the static block. Add a static method that prints both fields and demonstrates that they are both initialized before they are used.
  18. Create a class with a String that is initialized using “instance initialization.” Describe a use for this feature (other than the one specified in this book).
  19. Write a method that creates and initializes a two-dimensional array of double. The size of the array is determined by the arguments of the method, and the initialization values are a range determined by beginning and ending values that are also arguments of the method. Create a second method that will print the array generated by the first method. In main( ) test the methods by creating and printing several different sizes of arrays.
  20. Repeat Exercise 19 for a three-dimensional array.
  21. Comment the line marked (1) in ExplicitStatic.java and verify that the static initialization clause is not called. Now uncomment one of the lines marked (2) and verify that the static initialization clause is called. Now uncomment the other line marked (2) and verify that static initialization only occurs once.
  22. Experiment with Garbage.java by running the program using the arguments “gc,” “finalize,” or “all.” Repeat the process and see if you detect any patterns in the output. Change the code so that System.runFinalization( ) is called before System.gc( ) and observe the results.
t
  1. Créez une classe avec un constructeur par défaut (c'est à dire sans argument) qui imprime un message. Créez un objet de cette classe.
  2. Ajoutez à la classe de l'exercice 1 un constructeur surchargé qui prend une String en argument et qui l'imprime avec votre message.
  3. Créez un tableau de références sur des objets de la classe que vous avez créée à l'exercice 2. Mais ne créez pas les objets eux-même. Quand le programme s'exécute, voyez si les messages d'initialisation du constructeur sont imprimés.
  4. Terminez l'exercice 3 en créeant les objets pour remplir le tableau de références.
  5. Créez un tableau d'objets String et affectez une chaîne de caractères à chaque élément. Imprimez le tableau en utilisant une boucle for.
  6. Créez une classe Dog avec une méthode bark( ) (NDT: to bark = aboyer) surchargée. Cette méthode sera surchargée en utilisant divers types primitifs de données et devra imprimer différent types d'aboiement, hurlement, ... suivant la version surchargée qui est appelée. Ecrivez également une méthode main( ) qui appellera toutes les versions.
  7. Modifiez l'exercice 6 pour que deux des méthodes surchargées aient deux paramètres (de deux types différents), mais dans l'ordre inverse l'une par rapport à l'autre. Vérifiez que cela fonctionne.
  8. Créez une classe sans constructeur et créez ensuite un objet de cette classe dans main( ) pour vérifier que le constructeur par défaut est construit automatiquement.
  9. Créez une classe avec deux méthodes. Dans la première méthode, appelez la seconde méthode deux fois : la première fois sans utiliser this et la seconde fois en l'utilisant.
  10. Créez une classe avec deux constructeurs (surchargés). En utilisant this, appelez le second constructeur dans le premier.
  11. Créez une classe avec une méthode finalize( ) qui imprime un message. Dans main( ), créez un objet de cette classe. Expliquez le comportement de ce programme.
  12. Modifiez l'exercice 11 pour que votre finalize( ) soit toujours appelé.
  13. Créez une classe Tank (NDT: citerne) qui peut être remplie et vidée et qui a une death condition qui est que la citerne doit être vide quand l'objet est nettoyé. Ecrivez une méthode finalize( ) qui vérifie cette death condition. Dans main( ), testez tous les scénarii possibles d'utilisation de Tank.
  14. Créez une classe contenant un int et un char non initialisés et imprimez leurs valeurs pour vérifier que Java effectue leurs initialisations par défaut.
  15. Créez une classe contenant une référence non-initialisée à une String. Montrez que cette référence est initialisée à null par Java.
  16. Créez une classe avec un champ String qui est initialisé à l'endroit de sa définition et un autre qui est initialisé par le constructeur. Quelle est la différence entre les deux approches ?
  17. Créez une classe avec un champ static String qui est initialisé à l'endroit de la définition et un autre qui est initialisé par un bloc static. Ajoutez une méthode statique qui imprime les deux champs et montre qu'ils sont initialisés avant d'être utilisés.
  18. Créez une classe avec un champ String qui est initialisé par une « initialisation d'instance ». Décrire une utilisation de cette fonctionnalité (autre que celle spécifiée dans cet ouvrage).
  19. Ecrivez une méthode qui crée et initialise un tableau de double à deux dimensions. La taille de ce tableau est déterminée par les arguments de la méthode. Les valeurs d'initialisation sont un intervalle déterminé par des valeurs de début et de fin également donné en paramètres de la méthode. Créez une deuxième méthode qui imprimera le tableau généré par la première. Dans main( ), testez les méthodes en créeant et en imprimant plusieurs tableaux de différentes tailles.
  20. Recommencez l'exercice 19 pour un tableau à trois dimensions.
  21. Mettez en commentaire la ligne marquée (1) dans ExplicitStatic.java et vérifiez que la clause d'initialisation statique n'est pas appelée. Maintenant décommentez une des lignes marquées (2) et vérifiez que la clause d'initialisation statique est appelée. Décommentez maintenant l'autre ligne marquée (2) et vérifiez que l'initialisation statique n'est effectuée qu'une fois.
  22. Faites des expériences avec Garbage.java en exécutant le programme avec les arguments « gc », « finalize, » ou « all ». Recommencez le processus et voyez si vous détectez des motifs répétitifs dans la sortie écran. Modifiez le code pour que System.runFinalization( ) soit appelé avant System.gc( ) et regardez les résultats.
t t t
[27] In some of the Java literature from Sun they instead refer to these with the clumsy but descriptive name “no-arg constructors.” The term “default constructor” has been in use for many years and so I will use that. t [27] Dans certains articles écrits par Sun relatifs à Java, il est plutôt fait référence au terme maladroit bien que descriptif « no-arg constructors ». Le terme « constructeur par défaut » est utilisé depuis des années et c'est donc celui que j'utiliserai.
t t t
[28] The one case in which this is possible occurs if you pass a reference to an object into the static method. Then, via the reference (which is now effectively this), you can call non-static methods and access non-static fields. But typically if you want to do something like this you’ll just make an ordinary, non-static method. t [28] Le seul cas dans lequel cela est possible, est si l'on passe une référence à un objet dans la méthode statique. Ensuite, en utilisant la référence (qui est en fait this maintenant), on peut appeler des méthodes non-statiques et accéder à des champs non-statiques. Mais, en général, lorsque l'on veut faire quelque chose comme cela, on crée tout simplement un méthode non-statique.
t t t
[29] A term coined by Bill Venners (www.artima.com) during a seminar that he and I were giving together. t [29] Un terme créé par Bill Venners (www.artima.com) pendant le séminaire que lui et moi avons donné ensemble.
t t t
[30] In contrast, C++ has the constructor initializer list that causes initialization to occur before entering the constructor body, and is enforced for objects. See Thinking in C++, 2nd edition (available on this book’s CD ROM and at www.BruceEckel.com). t [30] En comparaison, C++ possède la liste d'initialisation du constructeur qui déclenche l'initialisation avant d'entrer dans le corps du constructeur. Voir Thinking in C++, 2nde édition (disponible sur le CDROM de cet ouvrage et à www.BruceEckel.com).
t t t
[31] See Thinking in C++, 2nd edition for a complete description of C++ aggregate initialization. [ Previous Chapter ] [ Short TOC ] [ Table of Contents ] [ Index ] [ Next Chapter ] Last Update:04/24/2000 t [31] Voir Thinking in C++, 2nde édition pour une description complète de l'initialisation par agrégat en C++.
t t t
t t t
t t
\\\
    
t t t
t
     
Sommaire Le site de Bruce Eckel