Assign value in a inner class

Suppose, we have the following two classes.
public class test{
final trythis t;
t = null;
doMethod(t); // because of this, t has to be assigned a null value
(new Thread(){public void run(){
    t = new trythis();  // t is assigned twice
  }}).start();
class trythis{
trythis(){
t seems to have to be defined as final, but final instance cannot be set in the inner class.
Does anyone know how to solve this problem?
Thanks

As the local variable has a lifetime of the executing method's
duration, you must ensure the innerclass (which has a longer lifetime)
has access to it by declaring it final.This is not quite exact. All this is due to the way inner classes are implemented. An inner class maintains the contents of the outer local variables used in two ways:
- If it is primitive, use the value verbatim (so the class has no relationship to the outer variable, it just uses the same number, so the local var needs to be final or else there could be surprises for a programmer who would think that changing the local var would also change the value used in the inner class)
- If it is a reference, copy it as a class member, and use that one wherever needed. For similar reasons as above, the two references have to be in sync, so the local var has to be final (the inner var can't change anyway)
This apply only to local variables because class members are accessible through a secret reference of the enclosing object passed in the constructor of the inner class. Static members are anyway accessible.
<teacher's mode off/>
<sorry for that, but someone might find the explanation useful :-)/>
By the way, the OP can get the value "t" out of the inner class by providing a special Thread subclass, ie
class MyThread extends Thread {
  public void run() {
    t = something;
  trythis t;
MyThread thread = new MyThread();
thread.start();
thread.join();
thread.t; //This is accessibleI'm not sure if this would be preferable to the array approach (which is ), but it is useful to know your alternatives

Similar Messages

  • How to pass a variable value to an inner class?

    Hi there,
    Please have a look of the code below. It's a bit long, but my concern is I did have to declare the int "i" variable as static because it is used by an inner class (if "i" is not declare as static, the code cannot be compiled).
    Is there a more "clean" way to do the way work without declaring the "i" int as static? (because the scope of this variable is not the whole program).
    Thanks for your help.
    Denis
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Runnable(){
                        public void run(){
                             myApp.jpb.setValue(Tools.i);//--- static variable i
                   for (int j=0; j<200; j++)
                        System.out.println(Tools.i+" - "+j);
    class myListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
              Thread t = new Thread() {
                   public void run(){
                        Tools.longTask();
              t.start();
    public class myApp {
         static JProgressBar jpb;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JPanel panel = new JPanel(new FlowLayout());
              jpb = new JProgressBar();
              jpb.setValue(0);
              jpb.setStringPainted(true);
              JButton button = new JButton("go");
              button.addActionListener(new myListener());
              panel.add(jpb);
              panel.add(button);
              frame.getContentPane().add( panel, BorderLayout.CENTER);
              frame.setVisible(true);
              frame.pack();
    }

    Without compiling it, writing it in notepad, it would be something like this. You should also wonder if this longTask has to be static by the way. But I think this demonstrates the inner class stuff. You can also look in the tutorial on this site: http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Innerclass(i));
                   for (int j=0; j<200; j++) {
                        System.out.println(Tools.i+" - "+j);
         Class Innerclass implements Runnable(){
              int i;
              public Innerclass(int i) {
                   this.i = i;
              public void run(){
                   myApp.jpb.setValue(Tools.i);//--- static variable i
    }

  • Swing - how to pass selected value out from actionPerformed() inner class?

    Hi all,
    I have a form with JcomboBox and textfields and I have to update the database
    with the submitted values. How can I pass the comboBox value out? I cannot defined boxValue as final outside the inner class.
    JComboBox list1 = new JComboBox (vector1);
    list1.addActionListener ( new ActionListener() {
    public void actionPerformed (ActionEvent ev) {
    boxValue = (String) ((JComboBox) ev.getSource()).getSelectedItem();
    thanks
    andrew

    OK, OK, my bad for not reading the whole post...
    1. Who needs to know the current JComboBox value? If the code that needs to know has access to the JComboBox, it can just get it from there. If the code is invoking the form, it is the responsibility of the form, not the listener, to return the values to the invoker.
    Please give us more information about what you are tryiug to do.

  • 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

  • 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);
    }

  • Anonymous inner class

    Hello
    In the following piece of code:
    import static tools.Print.*;
    interface ForInner {
         void who();
         String toString();
    class ForInnerWithParameters {
         int i;
         String s;
         ForInnerWithParameters(int i) {
              this.i = i;
    class NackedClass {
         public ForInner inner() {
              return new ForInner() {
                   private int i;
                        print("Inside inner class!");
                        i = 10;
                   public int getI() {
                        return i;
                   public void who() {
                        print("It's me, inner!");
                   public String toString() {
                        return "Anonymous class";
         public ForInnerWithParameters innerWith(int i, final String s) {
              return new ForInnerWithParameters(i) {
                   {     print("i = "+i);
                        print(s);
                        super.s = s;
                   public String getS() {
                        return s;
         public static void main(String[] args) {
              NackedClass nc = new NackedClass();
              ForInner fi = nc.inner();
              fi.who();
              ForInnerWithParameters fiwp = nc.innerWith(91, "Hello");
              print(fiwp.i);
              print(fiwp.s);
    i would like to assign to the variable s (inside ForInnerWithParameters class) the value "Hello" passed as a parameter in the main ( ForInnerWithParameters fiwp = nc.innerWith(91, "Hello"); )
    The method innerWith(int i, final String s) is getting the values 91 and "Hello". Both, the parameter in the method and the parameter in the class are named s. How can I assign the value s ("Hello") to the parameter s inside the class? this.s = s or super.s = s doesn't work. The only solution I found is to change either the name of the parameter s inside the method or the name of the parameter s inside the class.
    I hope the question is clear enough!
    Thanks a lot!

    I would have expected this.s to work, providing you used it every time (including getS()).
    But, to be honest, why bother? It's just pointlessly confusing to use s as your method parameter.

  • Assign collector to a profile class

    hi all,!
    just trying to assign collector to a profile class in receivables.. but cant find where to do it or any documentation that tells me!
    any advice?
    cheers!

    As the local variable has a lifetime of the executing method's
    duration, you must ensure the innerclass (which has a longer lifetime)
    has access to it by declaring it final.This is not quite exact. All this is due to the way inner classes are implemented. An inner class maintains the contents of the outer local variables used in two ways:
    - If it is primitive, use the value verbatim (so the class has no relationship to the outer variable, it just uses the same number, so the local var needs to be final or else there could be surprises for a programmer who would think that changing the local var would also change the value used in the inner class)
    - If it is a reference, copy it as a class member, and use that one wherever needed. For similar reasons as above, the two references have to be in sync, so the local var has to be final (the inner var can't change anyway)
    This apply only to local variables because class members are accessible through a secret reference of the enclosing object passed in the constructor of the inner class. Static members are anyway accessible.
    <teacher's mode off/>
    <sorry for that, but someone might find the explanation useful :-)/>
    By the way, the OP can get the value "t" out of the inner class by providing a special Thread subclass, ie
    class MyThread extends Thread {
      public void run() {
        t = something;
      trythis t;
    MyThread thread = new MyThread();
    thread.start();
    thread.join();
    thread.t; //This is accessibleI'm not sure if this would be preferable to the array approach (which is ), but it is useful to know your alternatives

  • Dynamically assign value to a column in ALV LIST Display

    Hi all,
    How can I dynamically assign value to a column in ALV LIST Display without using classes and methods?
    Thanks,
    Ridhima

    Hi Vikranth,
    I am displaying one ALV list say with columns A and B.
    I have value in A but not in B. Now at runtime user selects one row, clicks on push button in application toolbar, then i have to display value in column B in the already displayed list.
    I searched and came to know it can be done with oops concept. but i am not using classes and methods.
    so how can i do this?
    Thanks,
    Ridhima.

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • Assigning values to the charecterstics in a purchase order

    Hello,
    I have to create the configuration object and assign the values to it in a purchase order.
    I am able to generate the temporary CUOBJ using FM CUXM_SET_CONFIGURATION but not able to save it to the database.
    I am using FM CUCB_CONFIGURATION_TO_DB to save the cuobj to the DB but getting a short dump.
    MESSAGE_TYPE_X
    Technical information about the message:
    Message class...... "CUIB1"
    Number.............. 699
    And hence not able to run the FM 'CUCB_CONFIGURATION_TO_DB' properly.
    Can anyone help me how do I create the cuobj, assign values to it and then save it to the purchase order...
    Any help will surely be rubarbed...
    Thanks in advance.
    Husain

    Thank you for your respond, but I have few questions:
    myText = myText.replace(/\bred\b/gi, "<font color='#ff0000'><a href='event:redClick'>$&</a></font>");
    -myText.replace: how this finction works?
    -what is this?
    /\bred\b/gi
    -it's not a link , I need a hover listener to this spesific word.
    -where do you assign the word you want to highlight? And can I assign more than one word without writing the same code over again?
    -this looks like html and I don't use any in my project, can you write this line without html?
    <font color='#ff0000'><a href='event:redClick'>$&</a></font>
    I don't understand the functionality of these line:
    var pattern:RegExp = new RegExp("\(\?\<\=\\s)" + string + "(?=[\\s|\,])", "ig");
         var result:Object = pattern.exec(text);
         while (result) {
              textField.setTextFormat(highLightFormat, result.index, result.index + string.length);
              result = pattern.exec(text);
    what is
    RegExp?
    result?
    pattern.exec?
    Sorry if these are alot of questions, I just want to understand.

  • 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?

  • Inner Class Question

    My question pertains to the code at the bottom of this post.
    I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
    I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
    HERE'S THE CODE...
    class CreateInnerClasses {
         public static void main (String args[]) {
              ClassWithInnerClass cwic = new ClassWithInnerClass();
              ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
              //ClassWithInnerClass.regularInt = 5;
              ClassWithInnerClass.staticInt = 10;
              mic.printIt();
    class ClassWithInnerClass {
         public int regularInt ;
         static public int staticInt;
         class MyInnerClass {
              void printIt() {
                   System.out.println("Inside ClassWithInnerClass.myInnerClass");
         MyInnerClass retMyInnerClass () {
              return new MyInnerClass();

    The line    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
    On the other hand, the line    SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be    Outer.Inner instance = outerInstance.new Inner();In this case you could write:    ClassWithInnerClass.MyInnerClass mic =  new SomeClassWithAnInnerClass() . new InnerClass();
        // OR:
        ClassWithInnerClass.MyInnerClass mic =  cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
    http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

  • Reference to enclosing instance in inner class constructor

    Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) here
    super();
    class Global {
    public Global(int x) {

    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
    inner class always has an implicit reference to an
    instance of the enclosing class.Try this:
    class Outer {
    int m;
    class Inner extends Global {
    public Inner(int x) {
    super(x);
    protected void init(int x) {
    xxx = Outer.this.m + x; // Null pointer exception!!!
    class Global {
    int xxx;
    public Global(int x) {
    init(x);
    protected void init(int x) {
    xxx = x;

  • Setting variables from inner class

    I have a GUI that takes users information and provides a quotation as componants are clicked. My componants' Listeners are in seperate inner classes and from these I want to add certain details to variables, it seems to compile and run but it doesn't seem to be changing the value of the variable when the componants are clicked, is there any reason why this happens, my code is below:
    public class MyGUI extends JFrame{
            public MyGUI(){
              //GUI STUFF HERE
            double Price;
         private String total=calculate();
         public String calculate(){
              double aTotal=Price;
              return "$ " + aTotal;
         class MyListener implements ItemListener{
              public void itemStateChanged(ItemEvent evt){
                   if(evt.getSource()==rad1) {
                   Price=0.10;
                   else if(evt.getSource()==rad2) {
                   Price=0.12;
                        totalLab.setText(total);
    }

    shouldn't I also be able to access the outer classes methods? It doesn't seem to do this either.

  • Javadoc and inner classes

    So, I have an inner class that has some simple setter methods. The class is declared:
    private class ClassName...and the setter, like this:
             * sets the comment string
             * @param comment, the comment to assign
            public void setComment(String comment) {
                this.comment = comment;
            }and now I'm getting lots of warnings that look like this:
    warning - @param argument "comment," is not a parameter name.We are already using "private=true" in the build.xml
    Suggestions?
    Thanks,
    Glenn

    Remove the comma and it should work.

Maybe you are looking for

  • JDev 10.1.3 and JDK1.2.2 use javac problem

    I have an old application that I need to compile in 1.2.2, and have tried the "use javac" checkbox on the project properties compile page. The compiler seems to run, but there is an intential error in the code. I put it there, because the class file

  • How can I change the order of iCal calendars listed ON MY MAC?

    After upgrading to Lion the order of calendars listed on the left in iCal changed from my previous choice. I cannot modify the order by dragging a calendar to a different position in the list. I shall appreciate any suggestion to be able to have the

  • Does lifeproof nuud work with 5s?

    I'm wondering if anyone is using the Lifeproof Nuud for iPhone 5 on the new 5s and if so how well does it work?  Are you able to easily swipe up Control Center? Does the camera work well?

  • How to transfer iPhoto library to new computer?

    OK, I have an iMac G4 with iLife '06. I just got a new iMac G5 and I want to transfer my iPhoto library from the G4 to the G5 with all of my albums and folders. What is the best way to do it?

  • Installing itunes 7.6 and quicktime

    help - I have repeatedly tried to install itunes 7.6 and quicktime both individually and together. I repeatedly get an error message which says 'error creating directory QTsystem\Quicktime3GPP.Resources\ja.lproj' - I then get ererr 2330 and then I on