Page 1 of 1

Oracle's sample Java SE 7 Programmer I questions

Posted: Tue Dec 18, 2012 8:10 pm
by jklb
Oracle has a few sample questions for the certificate exam on http://education.oracle.com/pls/web_pro ... =SQ1Z0_803. One sample question has me baffled and I was hoping you could help. The question is this:

Code: Select all

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.

Can you explain this?

Thanks.

Re: Oracle's sample Java SE 7 Programmer I questions

Posted: Tue Dec 18, 2012 8:22 pm
by admin
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.

Re: Oracle's sample Java SE 7 Programmer I questions

Posted: Tue Dec 18, 2012 8:40 pm
by jklb
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?

Re: Oracle's sample Java SE 7 Programmer I questions

Posted: Tue Dec 18, 2012 11:38 pm
by jklb
I re-read your response and looked at the code and see what you mean. Where it says: type = "c";

I saw: String type = "c";

I think I've looked at this sample test twice before and each time I was stumped having assumed "type" was declared a local variable in Cougar.

Thank you.

Re: Oracle's sample Java SE 7 Programmer I questions

Posted: Mon Aug 19, 2013 1:13 am
by visweb
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.