Der Konstruktor sorgt dafür dass ein Objekt vollständig konfiguriert ist sobald du es erstellt hast. Du hast ja nicht lust jedesmal im nachhinein die beiden Werte zu setzen, das erledigt der Konstruktor für dich.
Genau so ist es. Wenn du alle deine Variablen auch schön private definierst, wirst du zudem keine unegwollten bösen Überraschungen bekommen, da der Zugriff nur über Getter/Setter erfolgt (mir schwant da schon wieder was...).
Also etwas derart:
Java:
String value = obj.getValue();
obj.setValue("neuer Wert");
/**
* Constructs an empty list with an initial capacity of ten.
*/publicArrayList(){this(10);}/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list.
* @exception IllegalArgumentException if the specified initial capacity
* is negative
*/publicArrayList(int initialCapacity){super();if(initialCapacity <0)thrownewIllegalArgumentException("Illegal Capacity: "+
initialCapacity);this.elementData =(E[])newObject[initialCapacity];}/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator. The <tt>ArrayList</tt> instance has an initial capacity of
* 110% the size of the specified collection.
*
* @param c the collection whose elements are to be placed into this list.
* @throws NullPointerException if the specified collection is null.
*/publicArrayList(Collection<?extendsE> c){
size = c.size();// Allow 10% room for growthint capacity =(int)Math.min((size*110L)/100,Integer.MAX_VALUE);
elementData =(E[]) c.toArray(newObject[capacity]);}
nehmen wir an ich definiere x und y vorher und schreibe folgendes:
public Konstruktor(String variable_1,String variable_2){
this.variable_1=variable_1;
this.variable_2=variable_2;
}
Danach erzeuge ich eine Objekt.
Konstruktor object =new Konstruktor(x,y);
nun ist variable_1 !=x
und variable_2!=y
aber der Konstruktor behandelt diese gleich,es ist nur verwirrend,ist es immer so?
Bei Methoden würde es ja nicht gehen,die Namen müssten ja übereinstimmen?
nehmen wir an ich definiere x und y vorher und schreibe folgendes:
public Konstruktor(String variable_1,String variable_2){
this.variable_1=variable_1;
this.variable_2=variable_2;
}
Danach erzeuge ich eine Objekt.
Konstruktor object =new Konstruktor(x,y);
nun ist variable_1 !=x
und variable_2!=y
aber der Konstruktor behandelt diese gleich,es ist nur verwirrend,ist es immer so?
Bei Methoden würde es ja nicht gehen,die Namen müssten ja übereinstimmen?