Bonjour,
Je suis en train de créer une application et je suis confronté au problème (peut être un faux problème) suivant :
J'ai une classe Element qui posséde 3 attributs (nom, type, path).
Lors de l'instanciation de cette classe, je peux avoir soit 1, soit 2, soit 3 des attributs transmis.
J'ai donc les constructeurs suivants :
Element(String nom, String path, char type)
Element(String path, char type)
Element(String nom, String path)
Element(String path)
Lorque ma classe est instanciée par le constructeur Element(String nom, String path), je determine le type dans le constructeur et ensuite, je souhaiterais instancier la classe en faisant appel au constructeur Element(String nom, String path, char type) qui valorise les attributs et effectue des contrôle.
Mais lorsque je mets en pratique, j'ai le message suivant :
"Constructor call must be the first statement in a constructor"
Lorsque l'objet est instancier par le constructeur Element (String nom, String path) je ne connais pas le type, je dois donc exécuter du code pour determiner le type en fonction de nom et path mais alors je ne peux plus finir l'instanciation en appelant mon constructeur Element(String nom, String path, char type).
D'où la question suivante :
Dois-je implémenter mon code de valorisation des attributs dans tous mes constructeurs ou mon problème vient-il d'une erreur de conception ?
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 import java.io.File; public class Element { private String nom; private String path; private char type; public Element(String nom, String path, char type) { this.setNom(nom); this.setPath(path); this.setType(type); } public Element(String nom, String path) { File file; file = new File(path); if(file.isDirectory()) { this(nom, path, 'D'); } } public Element(String path, char type) { } public Element(String path) { } private String getNom() { return this.nom; } private String getPath() { return this.path; } private char getType() { return this.type; } private void setNom(String nom) { this.nom = nom; } private void setPath(String path) { this.path = path; } private void setType(char type) { this.type = type; } }
Partager