Reputation: 97
I'm learning for my java certification and I came across this piece of code.
class Feline {
public String type = "f ";
public Feline() {
System.out.print("feline ");
}
}
public class Cougar extends Feline {
public Cougar() {
System.out.print("cougar ");
}
public static void main(String[] args) {
new Cougar().go();
}
void go() {
type = "c ";
System.out.print(this.type + super.type);
}
}
And when I run it, I get "feline cougar c c " so I get why it returns feline and cougar after it but why super.type refers to a Cougar object and not a Feline Object?
I saw this post but it didn't really enlightened me.
Upvotes: 0
Views: 141
Reputation: 2287
I would like to add one more thing here for completeness
public Cougar() {
System.out.print("cougar ");
}
This constructor is translated by the compiler like this
public Cougar() {
super(); // Added by compiler if not added explicitly by programmer
System.out.print("cougar ");
}
Thats why you get feline
first and then cougar
in output.
Other than that,there is only one type
variable involved as explained in other answers, so it is printing c
for both of them.
Upvotes: 1
Reputation: 1503839
super.type
is just referring to the same variable as this.type
... there's only one object involved, and therefore one field.
When you create an instance of a subclass, it doesn't create two separate objects, one for the superclass and one for the subclass - it creates a single object which can be viewed as either the superclass or the subclass. It has a single set of fields. In this case, you have a single field (type
) which originally had a value of "f "
, but whose value was then changed to "c "
.
Upvotes: 5
Reputation: 41
this-> invokes current class :Cougar super-> invokes Feline Feline is super class of Cougar because Cougar inherited from Feline. If you want to use Feline class fields in Cougar, You should use super.
You can see: http://www.instanceofjava.com/2015/03/this-vs-super-keywords.html
Upvotes: 1
Reputation: 394146
There is just one type
variable. Your Cougar
's go()
method sets it to "c ".
Therefore both this.type
and super.type
print c
.
Upvotes: 1