Final in inner class
I am trying to manually make a drawing program similar to this one
http://javafx.com/samples/Draw/
However I am running into issues involving inner classes and finals.
"local variable size is accessed from within inner class; needs to be declared final"
It wants me to make either SIZE or size a final. However once final, I can't change the variable.
I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
Any suggestions?
Thanks!
int SIZE = 1; //somewhere else
for( int size = 0 ; size < 5 ; size++){
Circle circle = new Circle(D/Padding);
circle.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent me){
SIZE = size;
);edit:
I am well aware this isnt neccesarily a javafx specific thing, but more of a general java poor programming knowledge.
I also know that the mouseadapter is an anonymous class and can only access final.
I am just looking for any suggestions on how to best handle this.
Edited by: namrog on Jul 5, 2011 10:51 AM
Edited by: namrog on Jul 5, 2011 10:59 AM
namrog wrote:
I am trying to manually make a drawing program similar to this one
http://javafx.com/samples/Draw/
However I am running into issues involving inner classes and finals.
"local variable size is accessed from within inner class; needs to be declared final"
It wants me to make either SIZE or size a final. However once final, I can't change the variable.Yes, that's the point. If a local variable is to be used by an instance of a nested class, that nested instance can live on long after the local variable goes out of scope. So it needs its own, separate copy of the variable. However, since, as far as we are concerned, there is only one variable, that variable needs to be final, so that there will not be issues with keeping the two copies' values coherent.
I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
Any suggestions?Create a final variable and copy the value of your non-final variable to it.
int nonFinal =...;
final int theFinalCopy = nonFinal;
new Whatever() {
void doStuff() {
doSomething(theFinalCopy);
}
Similar Messages
-
Why we are making a variable as final in method inner class ?
Why we are making the variable as final (method inner class) while we are accessing the method variable in inner class ?
regards,
namancAs far as I can tell, the only reason is to protect the programmer: when the inner class instance is constructed, it is given the then-current value of the variable. If the variable (or method parameter) later changes, the value held by the inner class would not. By making the variable final, the programmer doesn't have to worry about them staying in sync.
Here's some code to ponder:
public class InnerExample
void printMe( final int x )
Runnable runMe = new Runnable()
public void run()
System.out.println(x);
(new Thread(runMe)).start();
}When compiled with the Sun JDK 1.4.2, you get this bytecode:
void printMe(int);
Code:
0: new #2; //class InnerExample$1
3: dup
4: aload_0
5: iload_1
6: invokespecial #3; //Method InnerExample$1."<init>":(LInnerExample;I)V
9: astore_2
10: new #4; //class Thread
13: dup
14: aload_2
15: invokespecial #5; //Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
18: invokevirtual #6; //Method java/lang/Thread.start:()V
21: returnAt line (byte) 5, it loads the passed value onto the stack; at line 6, it invokes the inner class constructor (which is created by the compiler). Nothing in this sequence of code would prevent use of a non-final variable. -
Problem with final variables and inner classes
variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
Is there any solution to this?
Exception is:
java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
at java.awt.Component.processMouseEvent(Component.java:5131)
at java.awt.Component.processEvent(Component.java:4931)
at java.awt.Container.processEvent(Container.java:1566)
at java.awt.Component.dispatchEventImpl(Component.java:3639)
at java.awt.Container.dispatchEventImpl(Container.java:1623)
at java.awt.Component.dispatchEvent(Component.java:3480)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
at java.awt.Container.dispatchEventImpl(Container.java:1609)
at java.awt.Window.dispatchEventImpl(Window.java:1590)
at java.awt.Component.dispatchEvent(Component.java:3480)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291
-
Problem with final variables and inner classes (JDK1.1.8)
When using JDK1.1.8, I came up with following:
public class Outer
protected final int i;
protected Inner inner = null;
public Outer(int value)
i = value;
inner = new Inner();
inner.foo();
protected class Inner
public void foo()
System.out.println(i);
}causing this:
Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
public Outer(int value)
^
1 error
With JDK 1.3 this works just fine, as it does with 1.1.8 if
1) I don't use inner class, or
2) I assign the value in initializer, or
3) I leave the keyword final away.
and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
Reasons why I am trying to do this:
1) I can't use a newer JDK
2) I want to be able to assign the variables value in constructor
3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
4) I must be able to use inner classes
So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?You cannot use a final field if you do not
initialize it at the time of declaration. So yes,
your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
public class Outer {
protected final String str;
public Outer(String paramStr) {
str = paramStr;
Inner in = new Inner();
in.foo();
public void foo() {
System.out.println("Outer.foo(): " + str);
public static void main( String args[] ) {
String param = new String("This is test.");
Outer outer = new Outer(param);
outer.foo();
protected class Inner {
public void foo() {
System.out.println("Inner.foo(): " + str);
} producing the following:
[1:39] % javac Outer.java
[1:39] % java Outer
Inner.foo(): This is test.
Outer.foo(): This is test.
Is this then an "undocumented feature", working even though it shouldn't work?
However, I assume you could
get by with eliminating the final field and simply
passing the value directly to the Inner class's
constructor. if not, you'll have to rethink larger
aspects of your design.I guess this is the way it must be done.
Jussi -
Why only final variables can be accessed in an inner class ?
Variables declared in a method need to declared as final if they are to be accessed in an inner class which resides in that method. My question is...
1. Why should i declare them as final ? What's the reason?
2. If i declare them as final, could they be modified in inner class ? since final variables should not modify their value.(Got an error posting this, so I hope we don't end up with two...)
But what if i want to change the final local variable within that method instead of within anonymous class.You can't. You can't change the value of a final variable.
Should i use same thing like having another local variable as part of method and initializing it with the final local variable?You could do. But as in the first example I posted you are changing the value of the nonfinal variable not the final one. Because final variables can't be changed.
If so, don't you think it is redundant to have so many local variables for so many final local variables just to change them within that method?If you are worried that a variable might be redundant, don't create it. If you must create it to meet some need then it's not redundant.
Or is there any alternate way?Any alternate way to do what? -
HELP: Cannot refer to non-final variable inside inner class
Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
Can anyone offer any advice how to fix this?
static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
boolean bDone = false;
Element e;
SAXReader sax = new SAXReader();
FileInputStream fis = new FileInputStream( args.getInputFile() );
Document document = sax.read( fis );
Element root = document.getRootElement();
if( root.getName().equals( "Sheet" ) )
XMLParser.iterateElements( root, new XMLElementCallback()
public void onElement( Element element )
XMLParser.iterateAttributes( element, new XMLAttributeCallback()
public void onAttribute( Element element, Attribute attribute )
if( attribute.getName().equals( "guid" ) )
e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
// WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
Attribute a = (Attribute)it.next();
if( a.getName().equals( "randOffset" ) )
Integer i = new Integer( resolver.getTotalPermutations() );
a.setValue( i.toString() );
bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
if( ( !bDone ) && ( e != null ) )
Integer i = new Integer( resolver.getTotalPermutations() );
e.addAttribute( "randOffset", i.toString() );
FileOutputStream fileOut = new FileOutputStream( args.getInputFile() );
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter( fileOut, format );
xmlWriter.write( document );
fileOut.close();
}PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
Thanks in advance.It is already set to that - it does look correct in Eclipse, honest.
It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time. -
Why method local inner class can use final variable rather than....
Hi all
Just a quick question.
Why method-local inner class can access final variable defined in method only?
I know the reason why it can not access instance variable in method.
Just can not figure out why??
any reply would be appreciated.
StevenLocal classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.
-
Inaccessible with local variable(non-final) via method local inner class
Hi All,
Usually local variables, including automatic final variable live on the stack and objects & instanace variables live on the heap.The contracts for using the method local inner class should allow merely method final variable, not non-final stack variable.
Can anyone please clarify me ,behind the scene what is actual fact why method inner class should not access the stack(method) variable and only allow final variable?
Is anything correlated with the stack and heap aspects?
Thanks,
Stalin.G[email protected] wrote:
...behind the scene what is actual fact why method inner class should not access the stack(method) variable and only allow final variable?...explained by dcminter and Jardium in [an older thread|http://forums.sun.com/thread.jspa?messageID=10694240#10694240|http://forums.sun.com/thread.jspa?messageID=10694240#10694240]:
...Final variables are copied into inner classes - that's why they have to be declared final; to avoid the developer making an incorrect assumption that the local variable can be modified and have the change reflected in the copy.
When a local class uses a local variable, it doesn't actually use the variable. Instead, it takes a copy of the value which is contained in the variable at the moment the class is instantiated. It's like passing the variable to a constructor of the class, except that you do not actually declare any such constructor in your code.
To avoid messy execution flows to be present in a Java method, the Java language authors thought it was better to allow a single value to be present in such a variable throughout all its life. Thus, the variable has to be declared final.
...HTH -
Non-final variable inside an inner class - my nemisis
I have an issue with accessing variables from an inner method. This structure seems to allow access to the text objects but not to the button object. This comes from a bit of example code that just illustrates a simple form window with text fields and buttons that read them.
At the start of the class I have text objects defined like this:
public class SimpleGUI extends Composite {
Text nameField;
Text junkField;
// Constructors come next, etc...
Later within this class there is a method to create some GUI stuff, and then to create a button and when pressed access and print the text to the console
protected void createGui(){
junkField = new Text(entryGroup,SWT.SINGLE); //Ross
junkField.setText("Howdy");
Button OKbutton = new Button(buttons,SWT.NONE);
OKbutton.setText("Ok");
OKbutton.addSelectionListener(
new MySelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Name: " + nameField.getText());
System.out.println("Junk: " + junkField.getText());
And that all works fine. So within the inner class, the object junkField can be accessed nicely.
However if I try to do the same with the button (I want to change the label on the button after it's pressed) I get errors for trying to access a non-final object in an inner class.
I tried to handle the button similar to the text, adding this after the text defs:
Button myButton;
and under the println's in the inner class I wanted:
if OKbutton.getText.equals("OK") { OKbutton.setText("NotOK")}
That's when I get an issue with "cannot refer to a non-final variable inside an inside class defined in a different method"
Now, if I move the button declaration into the createGui method, and declare it with "final Button myButton" it works.
Why does the button need different treatment than the text?
Is this a suitable method to make my button change it's label when pressed, or is this sloppy?Button is a local variable. The anonymous inner class object you create can continue to exist after the method ends, but the local variables will not. Therefore, as the error message says, you must make that local button variable final if you want to refer to it inside the anon inner class. If it's final, a copy of its value can be given to the inner class--there's no need to treat it as "variable."
-
Anon inner classes + final vars
Ive always taken it for granted that anon inner classes can access outside variables only if they are static.
Googling this yields about the same information but no good explaination.
can someone kindly explain why the JVM wants this restriction? i suppose it must have something to do with the way objects are handled internally.
ill give dukes!The "final" restriction only applies to variables within a method which you want to use outside the method. I would assume it is down to
1) The variable goes out of scope when the method ends.
2) init().field and init.AnonActionListener().field would actually be different variables, changing init().field would not be replicated to init.AnonActionListener().field. This would be very confusing.
�8.1.3 does not give any reason for this. -
Compiler error when useing switch statements in an inner class
I have defined several constants in a class and want to use this constans also in an inner class.
All the constants are defined as private static final int.
All works fine except when useing the switch statement in the inner class. I get the compiler error ""constant expression required". If I change the definition from private static final to protected static final it works, but why?
What's the difference?
Look at an example:
public class Switchtest
private static final int AA = 0;
protected static final int BB = 1;
private static int i = 0;
public Switchtest()
i = 0; // <- OK
switch(i)
case AA: break; //<- OK, funny no problem
case BB: break; //<- OK
default: break;
private class InnerClass
public InnerClass()
i = 0; // <- OK: is accessible
if (AA == i) // <- OK: AA is seen by the inner class; i is also accessible
i = AA + 1;
switch(i)
case AA: break; // <- STRANGE?! Fail: Constant expression required
case BB: break; // <- OK
default: break;
}Thank's a lot for an explanation.Just a though:
Maybe some subclass of Switchtest could decalare its own variable AA that is not final, but it can not declare its own BB because it is visible from the superclass. Therefore the compiler can not know for sure that AA is final. -
Null pointer exception with inner class
Hi everyone,
I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
java.lang.NullPointerException
at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)
at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)
at Rotary$animateArea.paintComponent(Rotary.java:251)
at javax.swing.JComponent.paint(JComponent.java:808)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)
at javax.swing.JComponent._paintImmediately(JComponent.java:4668)
at javax.swing.JComponent.paintImmediately(JComponent.java:4477)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
Do inner classes have to be compiled seperately or anything?
Thanks a million for you time,
CurtinRI think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
This is the code for the applet:
import java.applet.*;
import javax.swing.JApplet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.image.*;
import java.util.StringTokenizer;
import java.net.*;
public class Rotary extends JApplet implements ActionListener, MouseListener
public boolean rotating;
private Timer timer;
private int delay = 1000;
private AffineTransform transform;
private JTextArea txtTest; //temp
private Container c;
private animateArea wheelPanel;
private JButton btPlay, btStop;
private BoxLayout layout;
private JPanel btPanel;
public Image wheel;
public int currentSector;
public String members[];
public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
final int TOTAL_SECTORS= 48;
//creates polygon array - each polygon represents a sector on wheel
public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
public void init()
members = new String[TOTAL_SECTORS];
coordsX= new int[TOTAL_SECTORS][4];
coordsY= new int[TOTAL_SECTORS][4];
currentSector = -1;
rotating = true;
transform = new AffineTransform();
//***********************************Create GUI**************************
wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
wheelPanel.setSize(600,580);
wheelPanel.setBackground(Color.yellow);
btPanel = new JPanel(); //create a panel for the buttons
btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
btPanel.setBackground(Color.blue);
btPanel.setMaximumSize(new Dimension(30,580));
btPanel.setMinimumSize(new Dimension(30,580));
btPlay = new JButton("Play");
btStop = new JButton("Stop");
//txtTest = new JTextArea(5,5); //temp
btPanel.add(btPlay);
btPanel.add(btStop);
// btPanel.add(txtTest); //temp
c = getContentPane();
layout = new BoxLayout(c,layout.X_AXIS);
c.setLayout(layout);
c.add(wheelPanel); //add panel and animate canvas to the applet
c.add(btPanel);
wheel = getImage(getDocumentBase(),"rotary2.gif");
getParameters();
for(int k = 0; k <TOTAL_SECTORS; k++)
polySectors[k] = new Polygon();
for(int n= 0; n<4; n++)
polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
btPlay.addActionListener(this);
btStop.addActionListener(this);
wheelPanel.addMouseListener(this);
startAnimation();
public void mouseClicked(MouseEvent e)
if (rotating == false) //user can only hightlight a sector when wheel is not rotating
for(int h= 0; h<TOTAL_SECTORS; h++)
if(polySectors[h].contains(e.getX(),e.getY()))
currentSector = h;
wheelPanel.repaint();
email();
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void email()
try
URL rotaryMail = new URL("mailto:[email protected]");
getAppletContext().showDocument(rotaryMail);
catch(MalformedURLException mue)
System.out.println("bad url!");
public void getParameters()
StringTokenizer stSector;
String parCoords;
for(int i = 0; i <TOTAL_SECTORS; i++)
{ //put member names in applet parameter list into an array
members[i] = getParameter("member"+i);
//separate coordinate string and store coordinates in 2 arrays
parCoords=getParameter("sector"+i);
stSector = new StringTokenizer(parCoords, ",");
for(int j = 0; j<4; j++)
coordsX[i][j] = Integer.parseInt(stSector.nextToken());
coordsY[i][j] = Integer.parseInt(stSector.nextToken());
public void actionPerformed(ActionEvent e)
wheelPanel.repaint(); //repaint when timer event occurs
if (e.getActionCommand()=="Stop")
stopAnimation();
else if(e.getActionCommand()=="Play")
startAnimation();
public void startAnimation()
if(timer == null)
timer = new Timer(delay,this);
timer.start();
else if(!timer.isRunning())
timer.restart();
Thanks so much for your help! -
SerialVersionUID and inner classes
Hello All
A quick question about serialVersionUID in inner classes.
If an inner class can't have any static members, how come it's legal to define
static final long serialVersionUID = 123L;
in an inner class ? Is there something special about serialization that allows this ?there is nothing special about the serialVersionUID defintion -
you can define static datamember of inner class as long as it is final or the inner class is static :
public class Out {
public Out() {
private class In {
static final int i1 = 1; //legal
static int i2 = 2; //** illegal
private static class InStatic{
static final int i1 = 1; //legal
static int i2 = 2; //legal
} -
Hello,
Can anyone tell me what the benefits of anonymous and inner classes are? inner classes are seem pretty complicated without any obvious benefit.
I have read about these in books and have some understanding of them but these don't appear to have any benefits.
Any info on either would be really cool.
regardsThere are many places where inner classes can be useful. One place where anonymous inner classes are particularly neat is for ActionListeners. For example, compare the "normal" way of doing it:
for(int i = 0; i < 2; i++)
JButton button = new JButton("Button " + i);
button.setActionCommand("ACTION" + i);
button.addActionListener(this);
public void actionPerformed(ActionEvent e)
if("ACTION0".equals(e.getActionCommand()))
doSomething(0);
else if("ACTION1".equals(e.getActionCommand()))
doSomething(1);
}with the way using anonymous inner classes:
for(int i = 0; i < 2; i++)
final int index = i;
JButton button = new JButton("Button " + index);
button.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
doSomething(index);
.In the first case you need a global actionPerformed method with some if statements inside. If there are many types of action then this can quickly become very large and error-prone. In the second case, each action is handled in its own class, right with the button that it's associated with. This is easier to maintain. Note that local variables must be declared final to be accessible from the inner class. -
I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
this language.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Bulb extends JPanel
private JButton push;
private Circle circle, circle2;
private final int DIAMETER = 100;
private final int X = 10;
private final int Y = 10;
public Bulb()
circle = new Circle(DIAMETER, Color.white, X,Y);
circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
push = new JButton("Turn on the Bulb");
push.addActionListener(new ButtonListener());
add(push);
setPreferredSize(new Dimension(500, 500));
setBackground(Color.black);
public void paintComponent(Graphics page)
super.paintComponent(page);
circle.draw(page);
private class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
// "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
// I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
// PARENT CLASS SUCH AS "PAGE."
circle2.draw(page);
}There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
They're not the same thing.
You can't use a local variable in your paintComponent method in a different method.
Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
Your event handlers are part of the controller. They should change the model.
Your paintComponent method is part of the view.
So the event handlers should change some data, e.g., add a note that a circle should be displayed.
Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it.
Maybe you are looking for
-
I noticed that since Macbooks.. macs in general use an EFI instead of BIOS. . .. Now i need to allocate some more RAM for the onboard video card since its currently running with an estimated 50mb.. I would like to increase this to 512 and cut the 3
-
New Hard Drive for my Macbook Pro
Hi guys, I will change my Hard Drive soon and thinking of the whole process triggered some questions in me . (my HD is fine but full, 120Gb) I went through the forum and already I got some precious informations such as how to remove and replace the H
-
Windowserver log entries: kCGErrorIllegalArgument:
I'm a newbie to Mac & OS X - I'm seeing lots of entries (sample below) in the log which I don't understand. Any help appreciated. Dec 09 11:18:23 [55] kCGErrorIllegalArgument: CGXSetWindowListTags: Operation on a window 0x2 not owned by caller Securi
-
Potential problem when using a template
Hi, I am fairly new to dreamweaver and I have created a template for my website, I am now using that template to produce a number of other pages. When I come to save it I save it as a new file,it is saving as a HTM file rather than a HTML file, is th
-
Bandwidth decrease in the inside network.
I just setup an asa5505, the isp give me 10MBPS. When I do a internet speed test before apply a IM inspect class map, I got 8MB aprox. after setup the IM inspection, the speed is reduced drastically to 2MBPS. The ASA5505 has 1mb of ram, the cpu never