Hi Leute.
Könnte mir irgendjemand erklären was genau das "this." in diesem Beispiel macht?
.this
In der Diskussion
Kommentare (6)
- Beliebt
- Neu
- Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Richi
2 Juni 2020, 21:34
Also this. ersetzt die Methodenvariable "alter = alter + 20" durch die public Objektvariable alter = 20.
Deswegen wird in :
System.out.println("Das Alter in alterAnpassen() ist " + alter); 20 angezeigt und nicht 40.
Aber im letzte System.out der mainmethode :
System.out.println("Angepasstes Alter: " + person.alter); wird 40 angezeigt obwohl da "this." ja noch da ist.
Das verstehe ich nicht ganz.
0
Gellert Varga
3 Juni 2020, 16:27
If you copy here the specific code you are talking about (Ctrl+C / Ctrl+V), and if you tell me what exactly you don’t understand and in exactly which line; then I will gladly to try to explain it (but just in english).
Please use the "Reply" button under my comment! (I will not get notification without this.)
0
Richi
3 Juni 2020, 17:06
So this. replaces the method variable "age = age + 20" with the public object variable age = 20.
Therefore in:
System.out.println ("Adjust the age in age () is" + age); 20 displayed and not 40.
But in the last System.out of the main method:
System.out.println ("Adjusted age:" + person.alter); is displayed 40 although there is "this." yes is still there.
I do not understand it entirely.
0
Gellert Varga
3 Juni 2020, 17:56
I'm sorry, but every small part would be very important for the understand.
I'm sorry, but i can't explain it this way.
It is "talk to the wind" for me.:)
Only if you attach the complete program. The whole program, without any changing.
After it i can show/explain you what does that program and how.
Again: You send me the program, and i will send back to You an explanation about it.:)
0
Richi
2 Juni 2020, 21:00
Ich verstehs so einigermassen
0
martin
2 Juni 2020, 10:44
this zeigt immer auf das aktuelle Objekt:
Beispiel:
public class Point {
public int x = 0;
public int y = 0;
//konstruktor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
innerhalb des Konstruktors musst du jetzt unterscheiden können, welches x du meinst - das Übergebene oder eben die Objektvariable. Und das kannst du mit this!
+3