this
, the keyword, has two separate jobs.
It's exactly like how +
means two completely different things in java: 5 + 2
does integer addition, "foo" + "bar"
does string concatenation. Same symbol, 2 unrelated jobs. In english, The word bank means both the land next to a river and also a financial institution. Same word, 2 unrelated jobs.
this
is no different.
- It means 'this object'. There is only one object here: An object of type Dog. There isn't 'a Dog object' and contained inside it a separate 'Animal super object'. That's not how it works. There is just the Dog object, which contains all fields - any fields you defined in Dog, and any field you defined in Animal.
Hence, this.someFieldDefinedInYourSuperClass = foo;
is fine, and that makes sense.
- It also means: Select a constructor. This version of the
this
keyword always comes with parentheses immediately following the keyword. this(params);
is what it looks like, and it lets you invoke one of your constructors from another one of your constructors. super()
is a similar construct that lets you call one of your super constructors. Note that all constructors must neccessarily use one of these; if you fail to do so the compiler injects super();
as first line in your constructor silently.
Example:
public Student(LocalDate birthDate, String name) {
this(generateNewStudentId(), birthDate, name);
}
public Student(String id, LocalDate birthDate, String name) {
this.id = id;
this.birthDate = birthDate;
this.name = name;
}
here the first usage is simply: Call the other constructor using the provided values. The second (and third and fourth) usages are the 'it is this object' variant.
In your example, you use super(name, age);
. This invokes the public Animal(String name, int age)
constructor from your superclass. It doesn't "set the name and the age" - it calls that constructor. What that constructor does? Who knows - you'd have to check the source. Maybe the constructor plays Feliz Navidad from the speakers first. You happen to know that it 'just' does this.name = name; this.age = age;
but that's just because that's what's currently in Animal.java
.
In contrast, this.name = name;
means "set the value of this object's name
field to the value of the name
parameter".