7. Given:
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);
}
}
What is the result?
A) cougar c c
B) cougar c f
C) feline cougar c c
D) feline cougar c f
E) Compilation fails
F) An exception is thrown at run time.
The correct answer is C. I expected D. I assume this is a test of shadowing, but I can't see how super.type could be shadowed.
Why do you think it is a test of shadowing? The instance field type is defined only in the base class. It is not redefined in the subclass. So there is only one "type" in Filine and nothing to shadow it in Couger.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
If it's true that there's nothing to shadow Feline's type (set to "f"), then why would "c" - the value of the local variable type in Cougar be printed?
Since the type var was never declared in the subclass (Cougar), the type in super is referenced, and that is the one that is changed by the go() method inside of Cougar. Since it is public, Cougar gets full access to the type var and can change it at will, as it does.
This is certainly a good example as to why vars should not be declared public. They should always be private.