Forums Register Login

inner class

+Pie Number of slices to send: Send

hello everyone

class Outer
{
class Inner
{
{
//this.display();
display();
}
}
void display()
{
System.out.println("Outer.display()");
}
}
here if I'm calling any method of outer class from inner class without using "this" then as inner object has reference to outer object so its able to access the outer class fields and methods.
but if i'm calling any outer class method or field using "this" then its compilation error that it can't find the method or field.why??
this is a reference to Outer$Inner object so it should have the reference to Outer object so it should have accessed Outer class members.
therefore my question is why in case of inner class this.display() is different from display(); ???

kindly answer soon.


thanks in advance.
+Pie Number of slices to send: Send
 

Roopam Samal wrote:kindly answer soon.


Kindly EaseUp (←click). We're all volunteers here.

I suspect you'll also get answers a lot quicker if you UseCodeTags (and please read the page thoroughly).

In general, the answer to any question like: "but if i'm calling any outer class method or field using "this" then its compilation error that it can't find the method or field.why??" is:
because you're doing something wrong.

In your particular case, if you want an instance of your Outer class, you can use Outer.this (JLS 15.8.4).

this on its own will always return an instance of the class where it is used.

Winston
For my next trick, I'll need the help of a tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 538 times.
Similar Threads
Anonymous Inner Class Question
inner classes
How to Contruct an Inner Class Instance
Inner classes
Inner Classes when to use them?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:06:34.