Why go for a static inner class than a regular static class

Hello,
What are the reasons to go for a static inner class? What benefits are available with a static inner class when compared to a static class?

When a class is an integral part of another class, it doesn't make sense to create a top level class for it.
Also there is no "static class" only static inner class.

Similar Messages

  • Why and how to use "inner class"

    When i am learning advanced java language features,
    i could not understand why and when to use the "inner class",
    who can give me some examples?
    Thanks!

    You would use an inner class when an object needs visibility of the outer class. This is akin to a C++ friend.
    An example of this is an iterator. An iterator over some collection is typically implemented as an inner class of the collection class. The API user asks for an Iterator (from the Collection) and gets one - in fact they receive an instance of an inner class, but doesn't care. The iterator needs to be inner, as the iterator needs to see the internal data structures of the outer (collection) class.
    This could also be done with an anonymous class, as mentioned by spenhoet above. However, in the case of a collection, the role of the iterator is clear - thus it deserves its own class. And often there is more than one place an iterator can be returned (e.g. see java.util.List, which has several methods that return Iterators/ListIterators), thus it must be put in its own class to allow reuse of the code by outer class.

  • Why interface for nodes? but class for UI Elements

    Hi Experts,
                    why in wda ,sap has given interface for nodes and elements ,and class for ui Elements.
    Eg. for using nodes they provide if_wd_context _node
          but for input field they provide cl_input_field
    Any Body Having an idea pls revert asap
    Regards
    Sarath

    hi sarath........
                when the node is being shared between 2 views.............. both the views need to access the same node for updating values. so you need an interface between these two.
               where as for elements you need not have any sharing..... and your element id is unique..... so no problem for that.
               where as in nodes... there might be a node of same name in your view as well as your component controller. so you need an interface.
    ---rergards,
      alex b justin

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • Creating Private Inner Classes in Separate Files

    I sometimes find myself wanting to use private inner classes to do things, but then moving the classes to separate files and giving them package access just because I don't like having single large files.
    Is there a way to create private inner classes on a class but just save them in another file?
    Thanks,
    John

    For me, short file sizes usually make design structure
    more clear. This can make maintenance easier. It can
    also make browsing the code easier, even if you have a
    good editor or IDE. It is also less intimadating
    psychologically (for me, anyway) to work with a number
    of small files, each one with a distinct purpose, than
    it is to open up a monster, even if the monster does
    represent a coherent design unit in some sense. I
    think this psychological impact may be more important
    than most people give it credit for.The psychological impact is lessened if you use an IDE like VisualAge (where only one method at a time is generally displayed) or use the "Show Source Of Selected Element Only" option in Eclipse.
    It's one thing to say a method should be short and a class should have as few methods as possible. Those forces reduce complexity and ease maintenance. It's another to say a source file should be short. A source file is just a storage artifact; source code could be stored in a database without changing how the programmer interacts with it. The fact that the standard java compiler requires the implementation of nested classes to be stored inside the source file of their containing class is a minor inconvenience. Don't let it discourage you from using inner classes when they make sense. The design should not be driven by source file size considerations.
    >
    But you have added code only with the sole intent of
    making a source file smaller. If Java had amechanism
    for storing nested classes in other files youwouldn't
    do this. My point below was that you shouldn't let
    source file size override the decision to use anested
    class.Why shouldn't I let it? There are plenty of
    non-trivial benefits (the ones I gave above, for
    starters) to working with smaller files.Because all of those benefits can be gained from using a decent IDE. Eclipse is free. It can show only the current method and it can collapse nested classes.
    You say "If
    Java had a mechanism...." Well, I could answer: It
    does have such a mechanism, and that mechanism is
    packages.Packages are not a mechanism for creating private inner classes in separate files. Eclipse has a mechanism for making the fact that they reside in the same source file a non-issue.
    >>
    I am not being cavalier. I have no argument, onlyan
    opinion.Again, you are perfectly entitled to your opinion.
    But if it is truly an opinion, and nothing more, why
    bother telling me about it. You might as well post
    your favorite color. It is the reasons for your
    opinion that interest me, and you still have not
    really given any.I have had lengthy arguments about the issue of method and class size. Like I said before, I prefer very small classes and methods. I also think the number of nested classes should be as small as possible. But I have no problem with large files. Files are just one way to organize source code. The size of the things in the files matters, not the files themselves.

  • Extending a member inner class

    I have a class
    public class A{
    class InnerClassB{
    Now the question is how to extend the inner class would it be
    class ExtendingInnerClassB extends A.B{
    or else?
    I am not sure anybody knows?

    Regarding inheritance from inner classes you must define your constructor:
    public ExtendedInnerClass(EnclosingClass EC) { EC.super(); }
    why?????
    well
    1. Where is the handle? The handle is an internal thing which is designed to accept the enclosing class. It is something which is not in the programmer's control. when there is an inner class, it is natural that the inner class cannot exist without its outer class. And that is the reason why the instantiation of an inner class is done using new OuterClass().new Innerclass(). U can see that the innerClass object is created based on the outer class object (assuming that the inner Class is not static). I hope that this is clear. Now .. the whole point is how does the compiler know that the Outerclass is the enclosing class? When the above line is compiled, the tricky handle in the inner class is assigned to the Outer class. So any reference henceforth is made based on this handle.
    2. In the Inherited Inner class, there is no way to assoicate the handle in the above manner. Hence we are forcing by calling the super().
    3 Otherwise why not simply create with: new InheritedInnerClass(EnclosingClass)? This is not possible. What if the inherited inner class needs a constructor in the above manner. That is assume that there is a class A. Then if the Inner Class needs the constructor to be InnerClass(A a, EnclosingClass b) for some other purpose, then what judgement can the compiler take? So that answers the question <b>Can't the compiler compile the inherited inner class assuming a handle to the enclosing class and then force an instance to be created using the EnclosingClass.new syntax?</b> Becuase in this case it cant go by any assumption.
    4. Maybe the compiler designers can make some change such that the inherited inner class should have all its constructors beginning with the enclosing object and there should be atleast one constructor. But somehow I feel that it is too much of asking.

  • Why do we go for inner classes in java?

    why cant we inherit the classes instead of having inner classes.
    what is the exact difference between the inner class and subclass.
    can anyone please explain me with some examples

    An inner class doesn't have any relationship with the outer class per se,
    except for one thing: an instantiation of the inner class can refer to the
    members of the instantiation of the outer class. One instantiation of the
    outer class can have many instantiations of the inner class 'circling
    around' it. Try to implement the following example using inheritance:public class Star {
         private String name;
         public Star(String name) { this.name= name; }
         public Planet addPlanet(String name) { return new Planet(name); }
         public class Planet {
              private String name;
              private Planet(String name) { this.name= name; }
              public Moon addMoon(String name) { return new Moon(name); }
              public class Moon {
                   private String name;
                   private Moon(String name) { this.name= name; }
                   public String toString() { return name+" (circling around "+Planet.this+")"; }
              public String toString() { return name+" (circling around "+Star.this+")"; }
         public String toString() { return name; }
         public static void main(String[] args) {
              System.out.println(new Star("sun").addPlanet("earth").addMoon("moon"));
    }kind regards,
    Jos

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

  • Why Inner class cannot access static variables

    Why is it that inner class can use only static final variables of the outerclass, and not ordinary static variables of the outer class. "Yes the JLS sepcifies that only final static variables can be used inside an inner class, esp a non blank final variable". But why this restriction.
    Thanks.

    so what are final static variables treated as if they
    are not variables. So if the final static value is
    not loaded when the class is loaded how will the
    class know about the value.??The actual value wil be substituted for the name of a static final value at compile time. That's why you can use them in switch statements where you can't use any variable variable.
    This is something to watch out for, by the way, because if you use a public static final value from one class in another the actual value will be compiled into the using class, so if you change the value where it's defined the class using it will have the old value until it's recompiled.

  • Reason for not allowing static declarations inside an inner class

    Is the reason for not allowing static declarations inside an inner class is due to the fact that it can never be accessed at a class level as the outer class has to create an instance of the inner class and any attributes/methods of the inner class has to be accessed through that.
    Typically, an instance (non-static) variable can never be accessed in a statement or expression inside a static context but the class variable can be accessed inside a non-static context. Given this, shouldnt the static declarations be allowed inside an inner class?
    Correct me if my understanding is wrong.
    Thanks

    I still couldnt get it clearly. Why i cant i have a static value ( variable ) for all the instances of the inner class irrespective of its enclosing instances of it ( i.e outer class instances). Say in this example below,
    class Outer
    static int i = 0;
    public Inner inner = new Inner();
    class Inner // inner class ( non-static nested class )
    int j = 0;
    static final int k = 2; // compile time constants are allowed
    // ininner class
    public void m1()
    j++;
    System.out.println("j is " + j);
    i++
    System.out.println("i is " + i);
    public static void main(String[] arg)
    Outer outer1 = new Outer();
    outer1.inner.m1(); // j will be 1 & i will be 1
    Outer outer2 = new Outer();
    outer2.inner.m1() // j will be 1 again & i will be 2. But I would
    // want j to be 2. Why is this not allowed?
    Looks like something missing..

  • Why can an inner.inner class not be static?

    First, look at these 2 classes:
    public class A1 {
    public A1() {
    new B1.C1();
    public class B1 {
    public static class C1 {
    public class A2 {
    public A2() {
    new B2.C2();
    class B2 {
    public static class C2 {
    Class A2 will compile just fine, but A1 will not saying that I can't define class C1 as static.
    Why not?
    Class C1 is not associated with an instance of B1 (because it's static), and we already have an instance of A1 (since we're in the constructor).
    Why is this so radically different that A2 (which works)?

    In class A1 the inner class B1 is just like a mehtod of class A1.
    So how we cant create static variable inside a method , similarly the class A1
    didnt accepting its inner class b! to create static class.
    (This is my assumption/view only, may be wrong)

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

  • Why inner classes cannot have static declarations ?

    Hi Friends,
    When i tried to make static declarations on a inner class which is non static, i am getting compilation error saying "inner classes cannot have static declarations". I want to know reason behind this implementation.
    Code which i have tried:
    public class TestOuter
    class TestInner{
    static int i =10;
    public static boolean validate(int a){
    if(a==0)
    System.out.println("Invalid data");
    return false;
    return true;
    public static void main(String a[]){
    boolean result = new TestOuter.TestInner.validate(0);
    System.out.println("Result="+result);
    Thanks,
    Shiju V.

    so I think if the
    outer class is not static , then Inner class can't be
    static as well. This is incorrect. An enclosed class can be indeed static while the outer is not, and vice versa.
    The difference between static/non static in regards to enclosed classes is that the static ones are 'top-level' and cannot access the members of the enclosing class.
    The effect of making an enclosed class static means there is only one instance of any variables, no matter how many instances of the outer class are created. In this situation how could the static inner class know which variables to access of its non static outer class. Of course the answer is that it could not know, and thus an static inner class cannot access instance variables of its enclosing class.
    Now, regarding non-static inner classes, and trying to give a valid answer to the original post:
    As with instance methods and variables, a non-static inner class is associated with an instance of its enclosing class and has direct access to that object's instance variables and methods.
    TestOuter outer = new TestOuter();
    TestOuter.TestInner inner = outer.new TestInner();Because an inner class is associated with an instance (inner class implicitly keeps a reference to the object of the enclosing class that created it), it cannot define any static members itself. Static members cannot access the this pointer.
    So, in an ordinary (non-static) inner class, the link to the outer class object is achieved with a special this reference. A static inner class does not have that special this reference, nor would a static method/variable of an ordinary (non-static) inner class.

  • Which one is better static inner classes or inheritance ?

    Hi,
    Consider following scenario,
    Class A does some database related work and Class B,C,D has more specific tasks for specific databases. For now B,C,D has more static information like driver name etc.
    1. I can either make class B,C,D as static inner classes OR
    2. classes B,C,D can extend class A.
    Case 1. makes it more flexible, if in future, B,C,D needs more than static methods.
    Case 2. can avoid complexity and cost of instantiating differnt objects based on differnt scenarios.
    Which approache is better in both ?
    Thanks

    Yes, I have seen abstract factory pattern , rather I have implemeted it at one place and in case 1. using abstract factory pattern is the way to initialize all classes.But my question is if I make all subclasses as a static inner classes, will it be better or efficient approach as compare to abstract factory pattern.Because Abstract factory patter adds more complications in code in turn it provides more flexibility.

  • EJB fails to compile - static inner class problem

    I am using OC4J 9.0.4 and Sun JDK1.4.2 and EJBs fail to compile if they reference objects that contain static inner classes. However, they successfully compile under JDK1.4.1.
    For example, I have a class like below:
    public class ValueObject
    public static class Key
    private Key key;
    private String value;
    Any references to ValueObject.Key inside the EJB cause the EJB compiler to generate "ValueObject$Key" which is incorrect. JDK1.4.1 is more lenient than 1.4.2, and allows this error through.
    Is there a way around this problem other than reverting to JDK1.4.1?
    Regards,
    Andy

    The reason I don't want to move to JDK 1.4.1 is because of the memory leak in the StringBuffer.toString() method.
    Is there anywhere I can submit this as a bug?
    Regards,
    Andy

Maybe you are looking for

  • Quark 6.5 Freezes after Security Update 2009-003

    Hi There, New to the forum. This has happened me before - couple of years back, something to do with Stuffit Preference Pane, doesn't seem to be the same solution. any help would be greatly appreciated. G

  • There was a problem connecting to the server "Max Time Capsule"

    Disclaimer:  Previously posted here (Ask Different) and similar to this. I'm trying to use my MBP inside and outside my office, and having it backup to my 2TB Time Capsule when on its wireless network, or defer backups when not on the Time Capsule's

  • Font looks corrupted with other language letters.

    Hi, I've had this problem for a while now, and I can't fix it no matter what I try... I use 4 types of keyboard layouts: Armenian - Western QWERTY, U.S., Canadian French - CSA, Turkish - QWERTY. On French or Turkish websites, extended latin character

  • .me accounts

    i am trying to back up my iphone because it is about to die.  my questions are as follows: 1) what is backed up on the cloud? just what you see when you log on right? the contacts and schedule. 2) to back up mail and notes, it asks me to start a free

  • Buying replacement battery

    My wife's 1.2GHz iBook's battery seems to be on its last legs as it holds a charge for less than an hour these days. I'm wondering if anyone has any experience or comments on buying cheap third party batteries as a replacement? I know Other World Com