When type='c'
is done in the subclass, it makes the super-class variable hidden, so that the super class variable is no longer available. Hence both this.type
and super.type
returns the value available ie, 'c', as type='f'
is not visible to the code.
At the same time, if we change type='c'
to String type='c'
here we are creating a local variable, and not overriding the super-class variables. Hence the solution for
public class Feline {
public String type = "f ";
public Feline() {
System.out.println("In 1....feline ");
}
}
public class Cougar extends Feline
{
public Cougar() {
System.out.println("2.....cougar ");
}
public static void main(String[] args) {
new Cougar().go();
}
void go() {
String type = "c ";
System.out.println(this.type + super.type);
System.out.println("Subclass type::"+type);
System.out.println("this.type::"+this.type);
System.out.println("super.type::"+super.type);
}
}
The output is::::::: In 1....feline
2.....cougar
f f
Subclass type::c
this.type::f
super.type::f
In this case a new local variable is created, therefore the super-class variable is not hidden