Reputation: 69
if i have a class Fish
public class Fish {
int numberOfFins;
int age;
public Fish(int age){
this.age=age;
}}
and class Shark that extends the Fish class
public class Shark extends Fish{
private int age;
public Shark(int age) {
super(age);
this.age=age;
}}
what age variable is accessed trough keyword this - is it of parent or from child class?
Thanks in advance?
Upvotes: 0
Views: 1910
Reputation: 1074168
Which age
you access depends on the type of the thing you use to access it. this
always has the type of the class the method or constructor belongs to — that is, in Fish
's methods/constructors, this
is of type Fish
. In Shark'
s methods/constructors, this
is of type Shark
. (There's only one object, which combines the features of Fish
and Shark
[yes, it really has two separate fields with the same name]; what we're talking about is the type of the reference to it.)
(Note that this is different for instance variables (like age
; aka "fields") than it is for instance methods. In Java, methods are polymorphic, instance variables are not.)
So within Fish
code, this.age
is Fish
's age
. Within Shark
code, this.age
is Shark
's age
.
E.g.:
public class Fish {
int numberOfFins;
int age;
public Fish(int age) {
this.age=age; // Sets Fish#age
}
}
public class Shark extends Fish {
private int age;
public Shark(int age) {
super(age);
this.age=age; // Sets Shark#age
}
}
This doesn't only apply to this
, it applies to variables as well. Look at main
below (and notice that I set the two age
s to different values; Shark
's age
is twice Fish
's age
):
class Fish {
int numberOfFins;
int age;
public Fish(int age) {
this.age = age; // Sets Fish#age
}
}
public class Shark extends Fish {
private int age;
public Shark(int age) {
super(age);
this.age = age * 2; // Sets Shark#age
}
public static void main(String[] args) {
Shark s = new Shark(10);
Fish f = s;
System.out.println(f.age); // 10
System.out.println(s.age); // 20
}
}
Upvotes: 3
Reputation: 6574
age will be inhereted from Fish but since you are decalring another variable with name "age" the inhereted variable will be hidden so what you will be having in your current object which is referenced by this is the variable declared in Shark
Upvotes: 0
Reputation: 31868
Within an instance method or a constructor,
this
is a reference to the current object — the object whose method or constructor is being called.
public Fish(int age){
this.age=age; / the one is Fish
}
Similarly in the other class, you have a member with the same name, which would be referenced in its c'tor :
public Shark(int age) {
super(age);
this.age=age; // the one in class Shark
}
Upvotes: -1