Oracle's sample Java SE 7 Programmer I questions

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
jklb
Posts: 17
Joined: Tue Dec 18, 2012 7:54 pm
Contact:

Oracle's sample Java SE 7 Programmer I questions

Post 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.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

jklb
Posts: 17
Joined: Tue Dec 18, 2012 7:54 pm
Contact:

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

Post 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?

jklb
Posts: 17
Joined: Tue Dec 18, 2012 7:54 pm
Contact:

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

Post 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.

visweb
Posts: 1
Joined: Mon Aug 19, 2013 12:44 am
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 45 guests