Are classes in Java static
or non-static
?
-
5you guys want me to go first?,ok sure..... WHAT?– st0leMar 13, 2011 at 8:59
-
2Why is this getting down votes!? The guy is clearly not in the know as to whether or not classes in Java are static. That makes it a valid, technical question.– Matthew CoxMar 13, 2011 at 9:08
-
I think the answer is 'No'. No it isn't. :)– NanneMar 13, 2011 at 9:12
-
it doesn't make sense for non-nested in any language to be "static" whatever that means. it is just a weird question to begin with. classes are a template for objects to be created from and that's fundamentally not "static" (whatever that means)– necromancerMar 13, 2011 at 9:17
6 Answers
Static
applies only to blocks, methods and class member variables. There's no meaning in having a Class Static, although an inner class can be static member of its enclosing class. Refer nested classes.
-
2+1 Saying that an (outer) class is static has as much meaning as saying that it's blue.– ThomasMar 13, 2011 at 9:18
-
3A
static
keyword on top-level (outer) class will actually produce compiler error. Mar 13, 2011 at 9:39
Classes are not static. only inner classes can be marked as static
public class NotStatic
{
static class StaticClass
{
}
}
That is the only type that can be static.
Edit:
public class NotAStaticClass
{
private static int foo;
public static int getFoo()
{ return foo; }
}
How will you statically instantiate this class? Answer, you cannot. You must still utilize the new operator.
NotAStaticClass s1 = new NotAStaticClass();
Were you perhaps asking if Java is a statically typed language? If so, then the answer is yes. See Wikipedia on Static Typing
Are you taking about Static inner classes or Static Methods or Static Variables ?
As Best practice avoid using static in following cases
- Avoid using Static in MultiThreaded Env.
- Avoid having Static methods in your Business logic layer, if not you may lose the advantages of OOPs such as inheritance, runtime polymorphism.
Concept of something being static is to get initialized only once i.e have only one copy in memory.. The same copy can be used whenever we want without creating another copy in memory again. So Classes being templates are not static ...
Classes cannot be static. Only methods, blocks, and variables within a class can be static, but not the class itself.