• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

reference

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A {
private static int counter;
public static int getCounter(){return counter++;}
private static int innerCounter;
public static int getInnerCounter(){return innerCounter++;}
private String name;
A() {name = "A" + getCounter();}
class B {
private String name;
B() {
name = "B" + getInnerCounter();
System.out.print(A.this.name + name); // 1
}}
public static void main(String[] args) {
new A().new B(); // 2
A a1 = new A();
a1.new B(); // 3
a1.new B(); // 4
}}


can anyone explain the output plz???
 
Ranch Hand
Posts: 1252
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(Edited no need to quote post just above)

What sort of confusion do you have??
[ July 19, 2006: Message edited by: Barry Gaunt ]
 
Shaan Shar
Ranch Hand
Posts: 1252
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

System.out.print(A.this.name + name); // 1
}}
public static void main(String[] args) {
new A().new B(); // 2
A a1 = new A();
a1.new B(); // 3
a1.new B(); // 4



Explanation for Line 1 & 2 #
"A.this.name" will refer to name variable of A class (Outer Class) and "name" is referring to inner class's variable.
that's why the output is "A0B0" In both classes now counter is reached to 1.

Explanation for Line 3 #

Now this line


Now this will print "A1B1" both counter increased to 2.

Explanation for Line 4 #

Now this time we are not creating any new object of outer class. so "Sample.this.name" will be ramain same as for line 3 # but still we are creating a new Object of Inner Class. that's why this time inner class counter will be increased after giving the output:

"A1B2"



This is the whole explanation of the code..

If still any concern then revrert back..with specific query.
 
reply
    Bookmark Topic Watch Topic
  • New Topic