• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Inner Class Question!!

 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following code:
public final class Test4 {
class Inner {
void test() {
if (Test4.this.flag); {
sample();
}
}
}
private boolean flag = true;
public void sample() {
System.out.println("Sample");
}
public Test4() {
(new Inner()).test();// line 1
}
public static void main(String args []) {
new Test4();
}
}
I had assumed it would not compile.The reason is that this inner class's instance should associate with it's enclosing class's instance. So when line 1 runs, there is no instance of enclosing class existing,but an inner class instance is created.
But in fact it can compile without problem.So am I missing something about the relationship between inner class's instance and enclosing class's instance.
Hope to clear me.
 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
In Constructor Test4(), you have just created an instance of the Inner class and called its test() method. Therefore there is no compile time error and hence you get the output "Sample".
An instance of a non-static innerclass is always associated with the instance of the outer class.
So, from the static main() method you can access the test() method of the Inner class only by creating an instance of the Inner class that is associated with the instance of the enclosing Outer class Test4.
You may try this...
...
...
public Test4()
{
// (new Inner()).test(); // line 1
}
public static void main(String args [])
{
// new Test4();
Test4.Inner i = new Test4().new Inner();
i.test();
}
...
- Suresh Selvaraj
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic