Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / July 2006

Tip: Looking for answers? Try searching our database.

inner class and static

Thread view: 
jim - 17 Jul 2006 19:43 GMT
I was told that the variable accessed inside a anonymous inner class
needs to be static.
However the followign code from Thinking in java 3 works fine.
Why?

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class Button2b extends JApplet {
 private JButton
   b1 = new JButton("Button 1"),
   b2 = new JButton("Button 2");
 private JTextField txt = new JTextField(10);
 private ActionListener bl = new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     String name = ((JButton)e.getSource()).getText();
     txt.setText(name);          ------question?  the txt is not final
but no complain from compiler
   }
 };
 public void init() {
   b1.addActionListener(bl);
   b2.addActionListener(bl);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   cp.add(b1);
   cp.add(b2);
   cp.add(txt);
 }
 public static void main(String[] args) {
   Console.run(new Button2b(), 200, 75);
 }
} ///:~
Matt Humphrey - 17 Jul 2006 23:58 GMT
>I was told that the variable accessed inside a anonymous inner class
> needs to be static.

An inner class (whether anonymous or not) may access the instance variables
of the outer class and it can access the local variables of the method that
instantiates it, provided they are final.

Cheers,
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/
Mike Schilling - 18 Jul 2006 00:00 GMT
>>I was told that the variable accessed inside a anonymous inner class
>> needs to be static.
>
> An inner class (whether anonymous or not) may access the instance
> variables of the outer class and it can access the local variables of the
> method that instantiates it, provided they are final.

Though a *static* inner class can only access static field of its enclosing
class (and can only call static methods of that class); pehshps that's what
the OP was thinking of.
jim - 18 Jul 2006 00:48 GMT
<Quote from TIJ3 chapter 8>
If you're defining an anonymous inner class and want to use an object
that's defined outside the anonymous inner class, the compiler
requires that the argument reference be final, like the argument to
dest( ). If you forget, you'll get a compile-time error message.
Feedback
</Quote>

The txt mentioned in the original post is an object that's defined
outside the anonymous inner class, but still the compiler didn't
complain, why?

> >>I was told that the variable accessed inside a anonymous inner class
> >> needs to be static.
[quoted text clipped - 6 lines]
> class (and can only call static methods of that class); pehshps that's what
> the OP was thinking of.
Stefan Ram - 18 Jul 2006 01:02 GMT
><Quote from TIJ3 chapter 8>
>If you're defining an anonymous inner class and want to use an object
>that's defined outside the anonymous inner class, the compiler
>requires that the argument reference be final, like the argument to
>dest( ).

 First, objects are not "defined": Objects are created at
 run-time and identifiers are declared at compile-time in Java.
 Also, finality is not an attribute of references but of
 identifiers.

 I can not understand why people recommend TIJ from this
 quotation (I never read more of it).
IchBin - 18 Jul 2006 06:21 GMT
>> <Quote from TIJ3 chapter 8>
>> If you're defining an anonymous inner class and want to use an object
[quoted text clipped - 10 lines]
>   quotation (I never read more of it).
>  

Yes, drop "TIJ". You should be reading a book like say: 'Effective Java:
Programming Language Guide' by Joshua Bloch.

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA              http://weconsultants.phpnet.us
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)
Oliver Wong - 20 Jul 2006 18:46 GMT
>  First, objects are not "defined": Objects are created at
>  run-time and identifiers are declared at compile-time in Java.
>  Also, finality is not an attribute of references but of
>  identifiers.

   I'm guessing you mean "Also, finality is not an attribute of objects,
but of identifiers/references".

   - Oliver
Mike Schilling - 18 Jul 2006 01:36 GMT
> <Quote from TIJ3 chapter 8>
> If you're defining an anonymous inner class and want to use an object
[quoted text clipped - 3 lines]
> Feedback
> </Quote>

Is that really what it says?  That's awful.  What it means to say is that
local and anonymous classes can access local variables and formal parameters
that are visible in their enclosing block. For this to work, these variables
must be declared final.  (Paraphrased from JLS 3, sec 8.1.3)

> The txt mentioned in the original post is an object that's defined
> outside the anonymous inner class, but still the compiler didn't
> complain, why?

It's a field in the enclosing class, not a local variable, so final isn't
necessary.
Tony Morris - 18 Jul 2006 11:50 GMT
> Though a *static* inner class can only access static field of its enclosing
> class (and can only call static methods of that class); pehshps that's what
> the OP was thinking of.

FWIW, "static inner class" is an oxymoron. You might mean "static nested
class". http://jqa.tmorris.net/GetQAndA.action?qids=67&showAnswers=true

Signature

Tony Morris
http://tmorris.net/

Mike Schilling - 18 Jul 2006 16:34 GMT
>> Though a *static* inner class can only access static field of its
>> enclosing
[quoted text clipped - 4 lines]
> FWIW, "static inner class" is an oxymoron. You might mean "static nested
> class". http://jqa.tmorris.net/GetQAndA.action?qids=67&showAnswers=true

Yes, that distinction is made at the top level.  But what about a local or
anonymous class defined in a static method?  I've never seen one of those
called a "nested class".

In other words, the terminology is fouled up.  There are really six
categories of classes defined within other classes, defined along two axes:

                       Instance     Static
Class-level       1                2
Local               3                4
Anonymous      5               6

For those defined at the class-level, "static" is a keyword.  For those
defined withing methods, it depends on whether they occur withing instance
or static methods.    The odd-numbered ones have encosing instances; the
even do not.

Now, what would you call 4 and 6, if not "static inner classes"?  For that
matter, why call everything besides 2 an "inner class", when the real
distinction is odd vs. even?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.