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.
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 "
.
See more on this question at Stackoverflow