B
bearice
as title.
as title.
as title.
Cultural note: It's considered polite to repeat the question inside the body
of the post to facilitate others' ability to read the conversation.
Inner classes can have static members, provided such members are compile-time
constants.
Asking "why" the language specifies something is an exercise in telepathy,
unless the language designers left some notes or blog entries or white papers
behind explaining the rational, which they might have done. GIYF.
I know that static members of inner classes would confuse me. Would such a
member only be static within the context of the immediately enclosing instance
of some instances of the inner class, or would it apply to all instances of
the inner class?
The problem is that inner classes are (generally) instantiated within an
instance of their enclosing class. Inner classes are not "static" enough on
their own for me to be comfortable with a "static" that operates across all
enclosing instance contexts. I suppose I could get used to it if Java were
defined that way, but it isn't. It's defined to make inner classes very
dependent on their enclosing instances.
If you want static members, use non-inner nested classes, or avoid nested
classes altogether.
Why is a static member of an inner class necessary for you? Why is an
alternative idiom not acceptable?
I'm not really need a static member in an inner class. just very
curious about it when the complier tells me it is an error.
Inner classes may not declare static initializers (§8.7) or member interfaces.
Inner classes may not declare static members,
unless they are compile-time constant fields (§15.28). ...
Nested classes that are not inner classes may declare static members freely,
in accordance with the usual rules of the Java programming language.
[email protected] said:Why inner classes can not have static members?
Lew said:Inner classes can have static members, provided such members are compile-time
constants.
I actually believe that's called a nested class and has differentStatic inner classes can have static members without such a restriction. This
is legal:
class Test {
static class Foo {
static int a;
public static void setA(int newA) {
a = newA;
}
}
}
Static inner classes [sic] can have static members without such a
restriction. This
is legal:
class Test {
static class Foo { // *not* an inner class
static int a;
public static void setA(int newA) {
a = newA;
}
}
}
Daniel said:I actually believe that's called a nested class and has different
semantics.
Anyway, Sun's Docs are your friend. Explained here in detail :
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html, see
Topic : "Inner classes" at the end of the page
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.