This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static instance variables and static methods

 
Shrini Kulkarni
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any body tell me why one can not have static instance variables and static methods within an inner class. But you can have something like
static final int a = 5;
in an inner class. Why ?
I have read this from JLS
class HasStatic{
static int j = 100;
}
class Outer{
class Inner extends HasStatic{
static final x = 3; // ok - compile-time constant
static int y = 4; //compile-time error,inner class
}
static class NestedButNotInner{
static int z = 5; // ok, not an inner class
}
interface NeverInner{}// interfaces are never inner
}
Thanks
Shrinivas

------------------
 
S Dave
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
an inner class depends on an instance of the outer class, unless it is static. it is therefore not allowed to have static variables in an inner class. however, if u make the inner class static, it would compile without error.
 
Priya Kannan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shrini,
you can have something like "static final int a = 5;" in an inner class b'cos compile time constants are allowed within an inner class and "static final int a = 5;" is a compile time constant.
JLS 15.28 says,
A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:
Literals of primitive type and literals of type String
Casts to primitive types and casts to type String
The unary operators +, -, ~, and ! (but not ++ or --)
The multiplicative operators *, /, and %
The additive operators + and -
The shift operators <<, >>, and >>>
The relational operators <, <=, >, and >= (but not instanceof)
The equality operators == and !=
The bitwise and logical operators &, ^, and |
The conditional-and operator && and the conditional-or operator | |
The ternary conditional operator ? :
Simple names that refer to final variables whose initializers are constant expressions
Qualified names of the form TypeName . Identifier that refer to final variables whose initializers are constant expressions
Examples of constant expressions:
true
(short)(1*2*3*4*5*6)
Integer.MAX_VALUE / 2
2.0 * Math.PI
"The integer " + Long.MAX_VALUE + " is mighty big."
and ofcourse our "static final int a = 5;"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic