Reputation: 2163
I'm struggling to understand how exactly to work out what 'this' refers to when used in superclass constructors.
I have three classes:
public class Animal {
public int x;
public Animal() {
this.x++;
System.out.println(this);
System.out.println(this.x);
System.out.println();
}
public String toString() {
return "Animal";
}
}
public class Mammal extends Animal{
public int x;
public Mammal() {
this.x++;
System.out.println(this);
System.out.println(this.x);
System.out.println();
}
public String toString() {
return "Mammal";
}
}
public class Dog extends Mammal{
public int x;
public Dog() {
this.x++;
System.out.println(this);
System.out.println(this.x);
System.out.println();
}
public String toString() {
return "Dog " + x;
}
public static void main(String[] args) {
Dog rover = new Dog();
}
}
The result of calling the Dog constructor is:
Dog 0 1
Dog 0 1
Dog 1 1
So when I call this.toString() in the Animal constuctor, this is referring to rover (the Dog). But when I do this.x++ in the Animal constructor, it is incrementing the x in Animal not in Dog.
Is that correct? Why does this.x++ not increment rover's x?
Upvotes: 0
Views: 99
Reputation: 4808
When you have this.x
while you have x
in both super class
and sub class
. The reference this.x
in subclass refers to the variable in subclass but not in super class. It's quite intuitive, because you are extending the super class to modify it to your needs and in OOP it's common to write subclass re declaring (I mean declaring variables with same name to customize or something like that) some variables. If you want the variable or method from super class
, particularly there is always super
keyword in your service.
Upvotes: 0
Reputation: 185
By declaring variable x in the subclasses of Animal you are actually shadowing the variable x of Animal, so this.x in Mammal refers to x in Mammal, which shadows x of Animal. In the Animal constructor of course, x refers to x in Animal, because the Animal class is not aware of any subclasses.
I do not know why you are shadowing x, removing public int x in all subclasses of Animal should result in the behaviour you expect. All subclasses of Animal will then refer to x declared in Animal.
More about shadowing in detail is found here: http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15
Hope I could help
Upvotes: 4
Reputation: 1871
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance.
Upvotes: 0