Method local Inner class

Why method local class can access only the final varaible of the method?
I found somewhere that this is because the non-final local variables go out of scope after method completion, but i wonder final local variables also reside on the stack.
class MyOuter2 {
private String x = "Outer2";
void doStuff() {
String z = "local variable";
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Local variable z is " + z); // Won't Compile!
} // close inner class method
} // close inner class definition
} // close outer class method doStuff()
}

pxNet wrote:
and so you are now saying it accesses the original variable, not a copy of it?No, I'm not saying that at all; see reply #1. The situation is quite the opposite, the inner class accesses a copy of the variable. Direct access to the local variable is most definitely not allowed. But that doesn't have anything to do with parameter-passing semantics.
I'll try to clarify with another demonstration of the problem. Assume that direct access to non-final local variables was actually allowed, and that the following example would compile (it won't, of course): class Outer {
    Inner method() {
        Object o = "foo";
        return new Inner() {
            public void modifyLocalVariable() {
                o = "bar";
    interface Inner {
        void modifyLocalVariable();
    public static void main(String[] args) {
        Inner inner = new Outer().method();
        inner.modifyLocalVariable(); // what local variable is this modifying?
                                     // the local variable in method() has gone
                                     // out of scope!
}Because of the way anonymous inner and local classes are implemented, they get a copy of the local variables (per the JLS). Mind you, there isn't any parameter passing going on at all in this example.
~

Similar Messages

  • 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.
    Steven

    Local 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

  • Method local Inner classes

    The local variables of the method live on the stack, and exist only for the lifetime of the method. You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren’t guaranteed to be alive as long as the method-local inner class object, the inner class object can’t use them. Unless the local variables are marked final! The following code attempts to access a local variable from within a method-local inner class.
    Can any one explaing me with an example of the above BOLDED text.

    Can any one explaing me with an example of the above BOLDED text
    class Outer {
         Outer outer;
         void method() {
              int i=0;
              class Local extends Outer {
                   int j = i;
              outer = new Local();
    }The above code doesn't compile unless the i variable in method() is declared final.

  • Local inner classes

    Hi all,
    Local inner classes can access all instance / static variables (include private) from enclosing class & local variables / methods parameters declared as final.
    class Outer {
    private int a = 0;
    static int b = 1;
    public void localInnerClassTest(final int k) {
    final double x = 0.4;
    class LocalInner {
    public void test() {
    System.out.println(a + " " + b + " " + k + " " + x);
    new LocalInner().test();
    public static void main(String args[]) {
    new Outer().localInnerClassTest(3);
    // shows 0 1 3 0.4
    I�ve seen in some mock exams that�s wrong ...
    Thankz

    Local inner classes can access all instance / static
    variables (include private) from enclosing class &
    local variables / methods parameters declared as
    final.Yes. That is correct
    >
    I�ve seen in some mock exams that�s wrong ...You've seen that what's wrong? - the statement you made above or the code you posted?
    The code you posted should not compile (is that what you mean by "wrong"), but you have not explained the problem you are having...
    Do you have a question you would like answered?

  • Local inner class

    *@author Rossi Kamal
    *version 1
    *easy local inner class
    public class local_inner
         final int Roll=10;
         public  void main(String args[])
              class _inner
                    int accountnumber=5;
                    int roll=Roll;
              _inner a=new _inner();
              System.out.println("Accoubtnumber"+a.accountnumber+"Roll"+a.roll);
    }

    Don't multi-post:
    http://forum.java.sun.com/thread.jspa?threadID=5130208&tstart=0

  • A question about local inner classes

    Suppose an inner class created in a method:
    public void thisMethod(final int a){
                 class InnerClass {
                   //code
    }Why, in order to use the parameter a in the inner class, I have to pass it final?

    Aurelious wrote:
    JoachimSauer wrote:
    Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
    Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
    On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
    So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable.

  • Local inner class scope

    Hello all,
    I am working out of "Thinking in Java" and ran across something I simply don't get. A method is called and passed an argument. This method defines an inner class and returns reference to it. Later a method in the inner class is invoked, but it still has access to the argument passed to the method that created the inner class and completed.
    Here is the code (shortened from the book):
    interface Counter {
         int next();
    } // close interface Counter
    public class LocalInnerClass {
         private int count = 0;
         Counter getCounter( final String name ) {
              class LocalCounter implements Counter {
                   public int next() {
                        System.out.print( name );
                        return count++;
                   } // close next()
              } // close inner class
              return new LocalCounter();
         } // close getCounter()
         public static void main( String[] args ) {
              LocalInnerClass lic = new LocalInnerClass();
              Counter c1 = lic.getCounter( "Local inner " );
              for( int i = 0; i < 5; i++ ) {
                   System.out.println( c1.next() );
              } // close for
         } // close main()
    } // close classAnd here is what is produced from running this:
    Local inner 0
    Local inner 1
    Local inner 2
    Local inner 3
    Local inner 4The string "Local inner" is passed to the method getCouter as a final String. getCounter creates the class and exits. Later a method in getCounter uses that final String "next". This is where I am lost - getCounter is done and gone, so how the heck is name accessible to the inner class?!?!
    Just when I thought I was getting the hang of this ;)

    So trying to redeem myself...
    You can use "javap -c" to see what a compiler is really doing.
    So using javap (version 1.4.2_04) on the inner class gives the following....
    class LocalInnerClass$1LocalCounter extends java.lang.Object implements Counter{
    LocalInnerClass$1LocalCounter(LocalInnerClass,java.lang.String);
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   aload_0
       5:   aload_1
       6:   putfield        #2; //Field this$0:LLocalInnerClass;
       9:   aload_0
       10:  aload_2
       11:  putfield        #3; //Field val$name:Ljava/lang/String;
       14:  return
    public int next();
      Code:
       0:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
       3:   aload_0
       4:   getfield        #3; //Field val$name:Ljava/lang/String;
       7:   invokevirtual   #5; //Method java/io/PrintStream.print:(Ljava/lang/String;)V
       10:  aload_0
       11:  getfield        #2; //Field this$0:LLocalInnerClass;
       14:  invokestatic    #6; //Method LocalInnerClass.access$008:(LLocalInnerClass;)I
       17:  ireturn
    The second method in the above is the next() method.
    The next() method uses the "getfield" bytecode to retrieve a member variable of the class which is named "val$name".
    The first method in the above is a constructor which takes a string as the only parameter. That string is saved in the member variable of the class called "val$name".
    It is preserving a reference, so if a StringBuffer was used rather than a String then one could alter the value in the for loop of the original code and see the change.

  • Methods or inner classes?

    Is there much difference, performance wise between a class method and an inner class? I am writing a 3d application where performance is of the essence, I can either put my code in seperate moethds or inner classes. The code is more managable when I use inner classes but I was wondering whether this was slower.
    Thanks.

    blink I presume your inner classes would have methods, right? Anyway,
    1. Don't prematurely optimise.
    2. Don't prematurely optimise.
    3. Object creation is the only thing which would cause any extra cost. But it's extremely unlikely to be a bottleneck.

  • Examples For 4 types of Inner Classes in java..

    Hi all,
    It would be gr8 help if u poeple provide me some examples in Java APIs for 4 types of Inner Classes.
    Normal Inner Class,Static Inner Class,Method Local Inner Class and Anonymous Inner Class.
    Thank you ..

    bprathibha wrote:
    ok... not to read..
    I was asked this question in an interview.
    I was unable to answer this question.I guess you know how to write a class?
    Normal Inner Class,Static Inner Class,Method Local Inner Class and Anonymous Inner Class.A normal inner class is a class that is written inside another class. A static inner class is the same thing as the normal inner class except that it's declared to be static. A method local class is a class that is declared within a method and it's only known within that method. An anonymous class is where you create a subclass and instantiate it at the same time. The construction if often used in UI programming. E.g.
    public void addListeners() {
        button.addActionListener(new ActionListener() { //Anonymous class
            public void actionPerformed(ActionEvent e) {
    }Kaj

  • Inner Classes doubts

    Hi All,
    I am trying to learn Inner classes in Java. I am referring to the book Core Java by Horstmann and Cornell.
    I know that there are various types of inner classes namely:
    - Nested Inner classes
    - Local Inner classes
    - Annonymous Inner classes
    - static inner classes
    First I am on with Nested Inner classes :
    Following is the code which I am executing :
    package com.example.innerclass;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    public class InnerClassTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TalkingClock clock = new TalkingClock(1000,true);
              clock.start();
    //          JOptionPane.showMessageDialog(null,"Quit Program");
    //          System.exit(0);
    class TalkingClock
         private int interval;
         private boolean beep;
         public TalkingClock(int interval, boolean beep){
              this.interval = interval;
              this.beep = beep;          
         public void start(){
              ActionListener listener = new TimePrinter();
              Timer t = new Timer(interval,listener);
              t.start();
         private class TimePrinter implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   Date now = new Date();
                   System.out.println("At the tone time is : "+now);
                   if(beep)
                        Toolkit.getDefaultToolkit().beep();
    }Following are my doubts :
    1. Why do we need to give the line
    JOptionPane.showMessageDialog(null,"Quit Program");
    System.exit(0);without this line the program doesn't show any output.
    2. I didn't understand this syntax.
    You can write inner object constructor more explicitly using the syntax. :
    outerObject.new InnerClass(construction parameters)
    For e.g.
    ActionListener listener = this.new TimePrinter();
    Here the outer class reference of the newly constructed TimePrinter object is set to this reference of the method that creates the inner class object. the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicilty naming it. For e.g if TimePrinter were a public inner class, you could construct a TimePrinter for any talking clock.
    TalkingClock jabberer = new TalkingClock(1000,true);
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    Please do help me understand this concept.
    Thanks
    Siddharth

    I have understood that this explanation :
    i) assuming that TimePrinter is an inner class of TalkingClock, that you'd need an instance of the later in order to create an instance of the former.Yes.
    Being a non-static inner class, it can not be instantiated out of context ... which context is the outer class.No. See my reply 11. The "context" is an instance of the outer class - it bears repeating.
    ii) jabberer is the outer instance that you are providing.Yes (more accurately it's a reference to an instance of the outer class, but that would be nit-picking).
    The left side is identifying the class, the right side is identifying the instanceNo.
    I'm not sure what you're calling left side and right side.
    If you're talking about both sides of the equals sign, then no, it's completely wrong.
    If you're talking about both sides of the "point" sign, then it's wrong too, just a bit less wrong.
    Let's revise this step by step (good thought process).
    1. in first line we are getting an outer class reference with this code
    TalkingClock jabberer = new TalkingClock(1000,true);
    this line is very natural and easily understood. Yes. The correct wording would be merely "we are getting a reference to an instance of the outer class". Sorry to insist densely.
    2. Now when we come to the second line, i.e. where we try to instantiate an inner class with this line of code
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    - I do understand the concept that we need an instance of outer class in order to create an instance of inner class as inner class is visible only to outer class.No. We need an instance of the outer class as the inner class is non-static, and by definition needs an instance of the outer class. That has nothing to do with visibility (public vs private vs...). Again, some words have special meanings in the Java world.
    - I also do understand that it cant be instantiated out of context. I see you like this expression, but it is too vague and misleads you. Please forget about it for a moment (no offense to otherwise helpful and knowledgeable abillconsl).
    - I also do understand that left side is identifying the class and right side is identifying the instance. ANDAgain I'm afraid of which "sides" you're talking about.
    - that in this line TalkingClock.TimePrinter listener = new TalkingClock().new TimePrinter();
    the outer class is anonymous (new TalkingClock()) as we don't require its name here Poor choice of words again. Anonymous classes do exist in Java, but are a totally different concept, that is not related to this line.
    - Also in this line TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    I understood the left side part i.e. TalkingClock.TimePrinter listener =
    We are attaching the outer class reference with the inner class that's absolutely understandable. Not at all!
    This just declares a variable listener, whose type is TalkingClock.TimePrinter (or more accurately com.example.innerclass.TalkingClock.TimePrinter).
    Then follows an assignment:
    WHAT I don't understand is the right hand side, i.e., the statement jabberer.new TimePrinter();
    1. I am unable to digest the fact that we can do something like anobject.new
    new is an operator that is used to instantiate an instance of an object. I am unable to digest that we can do x.new?See my previous reply. This is short-hand syntax Sun chose to pass a reference to an instance of the outer class (here, jabberer) to the constructor of the inner class. They could have chosen something else. Again, bear with it.
    I only know that we can do is new SomeClass(); AND NOT instance.new SomeClass();
    Now you know better:
    The second form is valid - only if SomeClass is a non-static inner class defined in a class of which instance is an instance.
    2. Is there something to this conceptually OR this is only a syntax and that I should learn it.
    I want to understand and grasp if there is some concept behind it rather than just learn and mug up. See my previous reply. Each instance of a non-static inner class stores a reference to an instance of the outer class. There must be a way (a syntax) to specify which instance (of the outer class) should be stored in the instance (of the inner class).
    This particular syntax is just a syntax, the "concept" is that the instance of the inner class stores a (unmodifiable) reference to the instance of the outer class that was specified when the instance of the inner class was created.
    I don't know if that deserves to be called a concept, but that's an interesting thing to keep in mind (there are some not-so-obvious implications in terms of, e.g. garbage collection).
    Best regards.
    J.

  • Getting my hands on var/methods of outer classes

    Hello,
    I am learning java these days (at school) and i ran into a problem having an action listener as a inner class, how do i get access to methods and variables of the outer class from the inner class ??
    for instance, this is my Outer class's constructor:
         public GBLEditor() {
              super("GridBagLayout Editor");
              ToolBar toolBar = new ToolBar();
              setJMenuBar(new MainMenuBar());
              getContentPane().add(toolBar, "North");
              Table tbl = new Table();
              getContentPane().add(new JScrollPane(tbl), "Center");
              getContentPane().add(new StatusPanel(), "South");
              MenuToolBarActionListener actionListener = new MenuToolBarActionListener();
              toolBar.getNewButton().addActionListener(actionListener);
              toolBar.getOpenButton().addActionListener(actionListener);
              toolBar.getSaveButton().addActionListener(actionListener);
              toolBar.getGenerateButton().addActionListener(actionListener);
              toolBar.getNewRowButton().addActionListener(actionListener);
              toolBar.getUpRowButton().addActionListener(actionListener);
              toolBar.getDownRowButton().addActionListener(actionListener);
              toolBar.getHelpButton().addActionListener(actionListener);
              setSize(770,300);
              setVisible(true);
    So if the button newRowButton is pressed in my toolbar, i need to access the tbl object's method getTableModel() from inside the inner class below (as far as i can see now)
    And this is my inner class:
    class MenuToolBarActionListener implements ActionListener {
              public void actionPerformed(ActionEvent e) {
    any ideas?

    Now your toolBar is local constructor's variable.
    Just declare it outside the constructor and you'll have access to it from methods of inner class.
    Something like this:
    public class GBLEditor extends ... {
        private Table tbl;
        public GBLEditor() {
            tbl = new Table();
        class MenuToolBarActionListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
               tbl.getTableModel();
    }

  • ActionListener and Inner Class Issue

    When I add ".addActionListener()" to buttons and create an inner class to listen/handle the action, my main class does not display the GUI. If I remove the ".addActionListener()" from the buttons and the inner class, the GUI displays. Below is my code. Anyone know what is wrong with my code?
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(new ButtonHandler());
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class package projects.web;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileBrowser{
         JFileChooser fileChooser = new JFileChooser();
         public FileBrowser(){
              int fileChooserOption = fileChooser.showOpenDialog(null);
         } // end constructor
    } // end class fileBrowser

    Encephalopathic wrote:
    Dan: When it doesn't display, what happens? Do you see any error messages? Also, please take a look at your other thread in this same forum as it has relevance to our conversations in the java-forums.org about whether to add GUIs to root containers or the other way around. /PeteI fiddled with the code some more and it seems that the problem is the inner code. When I changed from the inner class to the main class implementing ActionListener and had the main class implement the actionPerformed method, the GUI displayed and JFileChooser worked as well. I've add this version of the code at the bottom of this message.
    To answer your question: When it doesn't display, what happens? -- The web page loads and is blank. And there are no error messages.
    I took a look at the other thread is this forum (the one relates to our conversation in the other forum); the problem may be the way I've add the GUI. I'll try it the other way and see what happens.
    Thanks,
    Dan
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI implements ActionListener{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(this);
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Inner class inside a method - how does it access method's local variable?

    hello All:
    I've learnt that, an inner class, if defined inside a method, it can access the method's local variables, only when they are defined as "final".
    Anyone can help explain the rationale behind it?
    Thanks a lot!
    Sway

    fathomBoat wrote:
    In java, everything is about pass-by-reference.
    Wrong! Nothing in Java is ever pass-by-reference.
    Java uses pass-by-value everywhere.
    It makes sense to me if the reason of enforcing a variable to be "final" is to prevent it being messed up.No, the reason is that a copy is made and if the variable weren't final then it could change later on and the developer could be confused because his inner class didn't "see" that change.
    The variable being final prevents that scenario.
    However, if a copy of the variable is made inside the inner class, i dont see how possible it could affect variables outside of class?Such a copy is made, but the language designers wanted to hide that fact from the developer. By forcing all accessed variables to be declared final the developer has no way to realize that he's actually working on a copy.

Maybe you are looking for