• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

can a class be static?

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
preparing for scjp.I have one doubt.can a class be static?can it instanciated?what about its access?& above all when a class should be declared static?please help.
thanks in advance.
shaila
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Inner classes can be static, not outer classes. A static means that it belongs to the class and not to any instance of a class, so it wouldn't make sense to have an outer class static. That may help you remember this.
Inner classes can be static, but they are treated as top-level inner classes because they don't have all the free access to variables like non-static inner classes do.
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Classes can't be defined as static. However, you can achieve something similar in concept. The closest thiing that fits your description is a class of the following:
<pre>
public class A {
static int b;
static String = "justOne";
private A() {}
public static void amethod() {}
}
</pre>
Private constructor so no one can create an instance. All members are static. See java.lang.Math for example.
Another approach that's sort of similar is the singleton pattern. The idea is to only allow one single instance to be ever created. Static members are still allowed. An example of that is:
<pre>
public class A {
private int a;
public static int b;
private static A me;
private A() {}
public static A getInstance() {
if (me == null) {
me = new A();
}
return me;
}
public void aMethod() {}
}
</pre>
In this example, constructors are private. A public static method is provided to return the same instance at all times.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic