Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

inner classes

 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class G {
final String s1 = "G.s1";
class Z {
String s1;
void m1() {System.out.println(???);}
}
public static void main(String args[]) {
G g = new G(); g.new Z().m1();
}}

Which name or expression could be used in place of ??? to cause the program to print "G.s1"?

a. s1
b. G.s1
c. ((G)this).s1
d. G.this.s1
e. G.super.s1
f. None of the above

ans:-b
can anyone explain step by step
 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry the ans is "d" G.this.s1
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A couple things to note before I go through the list. The inner class has a variable s1 that hides the variable s1 in the outer class. Also, remember that the inner class does not extend the outer class in this case.

a. s1 - Wrong. Will attempt to use the variable s1 in the inner class.
b. G.s1 - Wrong. Fine if s1 was a static variable, but s1 is an instance variable.
c. ((G) this).s1 - Wrong. Cannot cast a reference of Z to a reference of G.
d. G.this.s1 - Correct. This is a legal way of accessing a variable in the enclosing context. Basically says to get s1 from object of class G that is tied to this instance.
e. G.super.s1 - Wrong. This tries to access a variable name s1 in the superclass of G. G extends Object, which has no such variable.
[ January 30, 2006: Message edited by: Craig Tyler ]
 
We've gotta get close enough to that helmet to pull the choke on it's engine and flood his mind! Or, we could just read this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic