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?

Similar Messages

  • Why is it that the interfaces cannot have static methods?

    why is it that the interfaces cannot have static methods?

    Interfaces contain polymorphic methods. Static methods are not polymorphic, and therefore would not make any sense to be in interfaces.

  • Help,about why we use inner class?

    Hi,
    when i read "java Tutorial"
    i found there is one chapter about inner class .
    i copy it down as follow.
    the context is about there is a class Stack, and this class want to implement some function of interface Iterator,but as the book said
    we should not let class Stack implement the Iterator directly, we should add a inner class inside the Stack .
    i know it's very import ,but i still can not understand the reason why add a inner class here.
    hope somebody can explain it a little more for me or give an example.
    thank in advance!
    Iterator defines the interface for stepping once through the elements within an ordered set in order. You use it like this:
    while (hasNext()) {
    next();
    The Stack class itself should not implement the Iterator interface, because of certain limitations imposed by the API of the Iterator interface: two separate objects could not enumerate the items in the Stack concurrently, because there's no way of knowing who's calling the next method; the enumeration could not be restarted, because the Iterator interface doesn't have methods to support that; and the enumeration could be invoked only once, because the Iterator interface doesn't have methods for going back to the beginning. Instead, a helper class should do the work for Stack.
    The helper class must have access to the Stack's elements and also must be able to access them directly because the Stack's public interface supports only LIFO access. This is where inner classes come in.
    Here's a Stack implementation that defines a helper class, called StackIterator, for enumerating the stack's elements:
    public class Stack {
    private Object[] items;
    //code for Stack's methods and constructors
    not shown
    public Iterator iterator() {
    return new StackIterator();
    class StackIterator implements Iterator {
    int currentItem = items.size() - 1;
    public boolean hasNext() {
    public Object next() {
    public void remove() {
    or you can visit here
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

    the context is about there is a class Stack, and this
    class want to implement some function of interface
    Iterator,but as the book said
    we should not let class Stack implement the Iterator
    directly, we should add a inner class inside the
    Stack .Simply because the implementation of the Iterator is nobody's business. By declaring it to be a private inner clss, nobody will ever know about it and only see the Iterator interface.

  • Why there should not be many static methods.

    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.

    shobhit123 wrote:
    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.The reason to discourage static methods is stylistic rather than technical. It encourages object oriented thinking.
    Each loaded class is represented by a Class object, and associated with that it a block of memory for static fields. As with all such storage this block is, as viewed from code, rather like an array with one, or in the case of double or long values, two slots per field.
    Because the class loader maintains a map from FQN to Class this storage is only released if the class loader that loaded it becomes unreachable, which happens only in situations like the un-deployment of a web application or EJB.
    Local variables for static methods are allocated in a stack frame, just as with instance methods. There's really no significant difference there.

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

  • Can you override a public static method?

    Can you override a public static method?

    A static method belongs to a class, not to a particular object, because you can call them without having an object instantiated. Methods are over rided which are inherited from an object. Since Static methods (although inherited) are not bound to a particular object, are not overridden.
    Though you have a method in the subclass with the same signatures but if you try to call super.____() you will get the error
    non-static variable super cannot be referenced from a static context

  • This latest version of Firefox is complete pants! Why can I no longer have a nice, tidy little row of icons across the top so that I click and find things at an instance like I could with the Google Toolbar?

    This latest version of Firefox is complete pants! Why can I no longer have a nice, tidy little row of icons across the top so that I can click and find things at an instance, like I could with the Google Toolbar?
    Example:- I've just spent 20 minutes looking how to 'translate' after I installed that add-on, there it was! A tiny little icon in the bottom right of the screen, I find the new set up very messy and very hard to navigate. Why can't I have the same set up on my toolbar that I've had for the last ten years? It's that bad that I'm even considering going back to I.E.
    Jon T

    Thanks but you're only telling me stuff I already know, that dosen't explain how I get the new version of Firefox to look neat and tidy like it always used to. I can no longer have all my icons that I use, I can no longer access things as easily as I could and the whole thing looks very bare and basic now! A bigger mess than even Google Chrome.
    I've spent most of this evening trying to get stuff back that is now lost because of this 'upgrade' and I'm now giving up with it. Well done! You've totally ruined what was the best browser for years.

  • Why can't a button have 'actions applied to it' in Flash CS3?

    Why can't a button have 'actions applied to it' in Flash CS3?
    I'm used to working with buttons in Flash MX and Flash 8 but
    after creating a button in Flash CS3, I'm getting text that reads
    'Current Selection Cannot Have Actions Applied To It' and so the
    actions menus are greyed out.
    What's the problem?

    There is nothing stopping you from producing files in the old
    ways. Go to the publish settings and select to publish as AS2. You
    can then use the techniques you are familiar with.
    However as dzedward points out, Actionscript has come a long
    way. The technique of putting the code directly on instances really
    went out with Flash MX in 2001 and for a long time now that wasn't
    the best way to do it. See this article by the very excellent David
    Stiller about it:
    http://www.quip.net/blog/2006/flash/museum-pieces-on-and-onclipevent
    So even if you aren't ready to take the plunge into AS3, I
    would recommend learning this style for all your AS2/1
    needs.

  • Why can I not just have a new phone.

    I am on my 3 refurbished replacement phone and am starting to get fustrated with Verizon. Every refurbished Galaxy S III that has been sent to me has had a different malfunction. Why can't I just have a new phone enstead of a refurbished one. 

    yaya09 wrote:
    I do carry the insurance and you are right about the contract but I am still fustrated that out of 3 replacement phones, all 3 have something wrong with them. And yes I did get my original phone at a discount price but it was still $300+  so it should of lasted longer than 6 to 7 months.
    Yes, it should, that's why they have a warranty, and the warranty says that after 14 days and up to 1 year, they will replace it with a refurbished device.
    If you buy a new car and have problems with the transmission after 6 months, do they give you a new car, or "refurbish" the one you have? (It's not like Verizon is doing something "new and different" with their warranty)

  • 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 global var can be initialized with a static method and not by other static global var declared after its usage

    Take this:
    class test
    static int i=j;
    static int j=10;
    this will give illegal forward reference ....
    but this will compile successfully ..
    class test
    static int i=test1();
    static test1()
    return 20;
    plz assume we have main method in both cases ..
    java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Plz help.
    Thanks
    Abhishek Roshan

    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Because the implementors of Java intentionally chose to do it that way.
    There are TWO stages to the process: preparation (which occurs first) and initialization.
    See the Java Language Spec section 12.4.1 'When Initialization Occurs
    The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
    Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
    Then if you check that referenced section 8.3.2.3 you will find this
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
    8.3.2.3. Restrictions on the use of Fields during Initialization
    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
      The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
      The usage is not on the left hand side of an assignment.
      The usage is via a simple name.
      C is the innermost class or interface enclosing the usage.
    When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.

  • Your Opinions: Inner Classes Need static Members

    Hi All,
    I want to solicit opinions for a minor change to the way inner classes work. I submitted this as an RFE to Sun and they rejected it, really without giving a reason. I'd like to know your opinions. If there is strong support I will repost the RFE.
    As you probably know, inner classes cannot have static members. The following generates a compiler error:import java.util.*;
    public class MyClass {
       class MyInnerClass {
          // Next line causes compiler error...
          static Map m = new HashMap();
    }In order to get around this you have to make the Map variable a static member of the containing class:import java.util.*;
    public class MyClass {
       static Map m = new HashMap(); // so much for encapsulation...
       class MyInnerClass {
    }I am suggesting that inner class be allowed to contain static members. Here's my reasoning...please comment:
    There are times when members (i.e., fields and methods) rightfully belong to the class as a whole, not to any particular instance of a class. I'm sure we've all found times when it was necessary to have static members in our classes. The same issues that necessitated using static members in top-level classes make them desirable for inner classes as well.
    Designing a class as an inner class is a step toward encapsulation. By forcing static members that logically belong in an inner class to be declared in the containing class is to crack the encapsulation, IMHO.
    Even though a containing class has access to all of an inner class' members (including private members) and vice versa, I think the notion of inner static members still is more OO-ish.
    What are your opinions? Would allowing inner classes to contain static members make Java more object oriented? I think it would.
    Technically, I don't think there's any reason this cannot work since the JVM has no notion of inner classes, per se.
    What do you think?

    an inner class is effectively a non static instance
    variable of its enclosing class. Instance member, but not a variable. it's a class, a type, not a variable.
    >
    I think the problem here is that making a field static
    means more than just that that field and its value are
    common to every instance of the class. It means that
    the value is valid without an instantiation of that
    class.
    Since the class itself must be instantiated (it is
    not static), What do you mean, excatly, by "_must_ be instantiated"? You are not ever "required" to instantiate anything unless you want to use it.
    you can't have static member data inside it. I don't see how this follows from the previous part of the statement.
    How would you reference the static member data of
    the inner class? You would have to specify an
    instance of the inner class, and since this breaks
    the meaning of static, you can't have static members
    in an inner class.How about outerObj.InnerClass.staticMember The syntax is well defined. The question at hand is, do we really want to allow this? The syntax to do this should only be an issue after that question has been answered in the affirmative. The people at Sun have decided not to allow it, so for now, syntax is a non-issue.
    >
    if you wanted a static member in an inner class you
    could put it in a super class of the inner class...Or in the enclosing class, as suggested in the orginal post.

  • What's the differences between a singleton and a class with static methods

    Hi everybody.
    My question is in the subject. Perhaps "differences" is not the good word. The positive and negative points ?
    Imagine you have to write a connection pool, sure you gonna choose a singleton but why ?
    Thank you very much.

    A class is a class. Java doesn't have (and I wish it
    did) a static outer class. Any class can extend
    another class or implement an interface.A Class object cannot extend or implement anything - it is not under programmer control in any way. You can create a class which implements interfaces, but calling static methods is completely unrelated. Interfaces only affect instance methods, not class ones. I think all of your comparison to C++ is actually confusing you more. In Java, there is a real class object at runtime, as opposed to C++.
    YATArchivist makes a good point about being able to
    serialize, altho I've not met that desire in practice.
    Maybe a concrete example would help.
    mattbunch makes another point that I don't understand.
    A class can implement an interface whether it sticks
    its data in statics or in a dobject, so I guess I
    still don't get that one.See my comment above. Static methods are free from all contractual obligations.
    I prefer instance singletons to singleton classes because they are more flexible to change. For instance I created a thread pool singleton which worked by passing the instance around, but later I needed two thread pools so I made a slight modification to the class and poof! no more singleton and 99% of my code compiled cleanly against it.
    When possible, I prefer to hand the instance off from object to object rather than have everything call Singleton.instance() since it makes changes like I mentioned earlier more feasible.

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

Maybe you are looking for

  • Problem opening trial version of lightroom

    Hello -- Would appreciate some help.  My trial version of Lightroom opened and ran without problems for a few days (in Win XP), but now will not run.  When I attempt to open it I receive the following message: "Lightroom opening catalog: P1030035.JPR

  • Purchasing a MacPro, worried about Leapard upgrade

    Ok, so longterm PC user, finally getting my first Mac. Pretty sure I want the MacBook Pro 17 inch. Mobility + Power. My worry is this: Leapard looks amazing, and somewhat demanding. Being that it comes out in October (I believe), am I better off wait

  • Can I use time capsule for tranfering entire computer.

    I have a new macbook that Apple messed up on and I am having to send back. I will be getting the ne 17'macbook instead. I am hoping that if I use time capsule and time machine I will be able to put all applications and data from the macbook, send bac

  • I am so mad right now

    ok so i exported mpeg1 using compressor and had lots of marks which i made sure were marked as chapter markings. I thought that compressor kept chapter markings, but apparently not cause i imported the mpeg1 to DVDSP and lo and behold, no markings. A

  • Win XP and Raid 0+1

    I'm new to Raid and I'm just looking for some general answers.  Any help would be greatly appreciated.   Does anyone know if Windows XP Pro, for any Service Pack, can run a Raid 0+1? If so, could I start the Raid format on a Hard Drive, with 3 other