2016-05-28 8 views
-1

ich zwei Konstrukteurs bekam:Wie Nummer automatisch im Constructor Java machen

private int num ; 
private Room room ; 
private boolean status; 
private E_types type ; 

1-: Partielle Constructor:

Instrument(int num) 
Partial Constructor ~ use for initial key fields 

2-: Voll Constructor:

Instrument(Room room, boolean status, E_Types type) 
Full Constructor ~ use for initial all fields instruments should be numbered automatically 

Was ist das automatisch nummeriert?

Thanks :)

+1

Woher haben Sie diesen Code? –

+0

* "Was ist das automatisch nummeriert?" * Du wirst fragen müssen, wer dir die Aufgabe gegeben hat, was sie damit meinen. Wir könnten * raten *, aber sie werden * wissen *. –

+0

Ich denke, sie bedeuten mit "automatisch nummeriert", dort Standard-oder Anfangswerte. –

Antwort

0

Sie benötigen die static Variable in der Klasse, die automatisch mit jedem Instrument geschaffen erhöhen. Einfach zu erklären, was static bedeutet: Es ist eine Variable für alle Instanzen einer Klasse zusammen. Lassen Sie es zu num zuweisen.

public class Instrument { 
    private static int id = 0; // representing ID 
    private int num = 0; 
    private Room room ; 
    private boolean status; 
    private E_types type ; 

    public Instrument(Room room, boolean status, E_Types type) { 
     Instrument.id++; 
     this.num = Instrument.id; 
     this.room = room; 
     this.status = status; 
     this.type = type; 
    } 

    public static int getID() { 
     return Instrument.id; 
    } 

    public int getNum() { 
     return this.num; 
    } 
} 

ist es an einem Beispiel Lassen Sie versuchen. Lassen Sie uns 4 Instrumente auf Basis des obigen Konstruktors erstellen und rufen Sie den Getter und die statische Methode die maximale ID zurück.

Instrument a = new Instrument(...); 
Instrument b = new Instrument(...); 
Instrument c = new Instrument(...); 
Instrument d = new Instrument(...); 

System.out.println(c.getNum()); // prints 3, num of "c" instrument 
System.out.println(Instrument.getID()); // prints 4 (total of instruments) 
+0

Danke, ich habe es versucht und es funktioniert! Also müssen wir statisch verwenden, wenn wir etwas benötigen, das für alle Objekte freigegeben ist? Recht ? –