Différentes façons de créer un objet en Java
Création d'objets d'une classe en Java
Il existe cinq manières différentes de créer un objet et nous verrons ci-dessous les manières de créer un objet :
- Utilisation du "nouveau" mot-clé
- Utilisation de la méthode "newInstance()" de Class.
- Utilisation de la méthode clone()
- Utilisation de la méthode "newInstance()" de la classe Constructor
- Utiliser la désérialisation
1) Utiliser le "nouveau" mot-clé
- new est un mot-clé introduit en Java.
- Nous utilisons principalement le nouveau mot-clé pour créer un objet.
- En utilisant le nouveau mot-clé, nous pouvons appeler n'importe quel constructeur que nous voulons appeler.
Exemple :
class CreateObjectByNew { // Default Constructor CreateObjectByNew() { System.out.println("We are creating an object by using new keyword"); } } class Main { public static void main(String[] args) { // Creating an object of CreateObjectByNew class CreateObjectByNew cobn = new CreateObjectByNew(); } }
Sortie
E:\Programs>javac Main.java E:\Programs>java Main We are creating an object by using new keyword
2) Utilisation de la méthode "newInstance()" de la classe.
- Cette méthode newInstance() est disponible dans Class.
- En utilisant la méthode newInstance() de Class, il peut appeler le constructeur sans argument ou le constructeur par défaut.
- Cela crée une nouvelle instance de la classe.
Exemple :
class NewInstanceMethodOfClass { // Default constructor NewInstanceMethodOfClass() { System.out.println("Object by using newInstance() method of Class"); } } class Main { public static void main(String[] args) throws Exception { // Creating an object of Class class and // we are passing our class as an argument // in forName() method of Class Class cl = Class.forName("NewInstanceMethodOfClass"); // Now we are calling newInstance() method of Class // and returns a reference of our created class NewInstanceMethodOfClass nimoc = (NewInstanceMethodOfClass) cl.newInstance(); } }
Sortie
E:\Programs>javac Main.java E:\Programs>java Main Object by using newInstance() method of Class
3) Utilisation de la méthode clone()
- Cette méthode est disponible dans l'interface java.lang.Cloneable.
- Nous avons remplacé la méthode clone() de l'interface Cloneable dans notre classe.
- C'est le moyen le plus simple de copier un objet.
Exemple :
class CreateObjectByClone implements Cloneable { String name; CreateObjectByClone(String name) { this.name = name; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public static void main(String[] args) throws Exception { CreateObjectByClone cobc1 = new CreateObjectByClone("Preeti"); CreateObjectByClone cobc2 = (CreateObjectByClone) cobc1.clone(); System.out.println("The values before clone() in cobc1" + " " + cobc1.name); System.out.println("The values after clone() in cobc2" + " " + cobc2.name); } }
Sortie
E:\Programs>javac CreateObjectByClone.java E:\Programs>java CreateObjectByClone The values before clone() in cobc1 Preeti The values after clone() in cobc2 PreetiPublicité
4) Utilisation de la méthode "newInstance()" de la classe Constructor
- Il crée également une nouvelle instance d'une classe similaire à la méthode newInstance() de la classe Class.
- En utilisant la méthode newInstance() de la classe Constructor, il peut appeler n'importe quel nombre de constructeurs d'arguments.
Exemple :
import java.lang.reflect.Constructor; class NewInstanceMethodOfConstructor { String fname, lname; // passName() method with two argument public void passName(String fname, String lname) { this.fname = fname; this.lname = lname; } } class Main { public static void main(String[] args) { try { // calling constructor and returns a reference of Constructor class Constructor cons = NewInstanceMethodOfConstructor.class.getDeclaredConstructor(); // Now we are calling newInstance() method of Class // and returns a reference of our created class NewInstanceMethodOfConstructor nimoc = (NewInstanceMethodOfConstructor) cons.newInstance(); nimoc.passName("Preeti", "Jain"); System.out.println("My full name is :" + nimoc.fname + " " + nimoc.lname); } catch (NoSuchMethodException ex) { System.out.println(ex.getMessage()); } catch (SecurityException ex) { System.out.println(ex.getMessage()); } catch (InstantiationException ex) { System.out.println(ex.getMessage()); } catch (IllegalAccessException ex) { System.out.println(ex.getMessage()); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
Sortie
E:\Programs>javac Main.java E:\Programs>java Main My full name is :Preeti Jain
5) Utiliser la désérialisation
- Lorsque nous sérialisons un objet, puis après le désérialisons, la JVM de l'environnement d'exécution crée un objet distinct pour cela.
- Dans le cas de la désérialisation, il n'appelle aucun constructeur pour créer un objet.
- Notre classe doit implémenter l'interface Serializable.
- Nous allons utiliser deux classes nommées ObjectOutputStream et ObjectInputStream et leurs deux méthodes writeObject() de ObjectOutputStream et readObject() de ObjectInputStream.
- writeObject() :cette méthode sérialise un objet et le transfère dans le flux de sortie.
- readObject() :cette méthode fait référence à un objet hors du flux, puis le désérialise.
Exemple :
// Java program to demonstrating serialize and deserializing an object import java.io.*; class Serialize implements Serializable { public String fname, lname; public Serialize(String fname, String lname) { this.fname = fname; this.lname = lname; } } public class Deserialization { public static void main(String[] args) { Serialize serialize = new Serialize("Ronit", "Jain"); try { FileOutputStream fos = new FileOutputStream("E:\\Programs\\myjava.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(serialize); oos.close(); fos.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); } serialize = null; try { FileInputStream fis = new FileInputStream("E:\\Programs\\myjava.txt"); ObjectInputStream ois = new ObjectInputStream(fis); serialize = (Serialize) ois.readObject(); ois.close(); fis.close(); System.out.println("His full name is :" + serialize.fname + " " + serialize.lname); } catch (IOException ex) { System.out.println(ex.getMessage()); } catch (ClassNotFoundException ex) { System.out.println(ex.getMessage()); } } }
Sortie
E:\Programs>javac Deserialization.java E:\Programs>java Deserialization His full name is :Ronit Jain