Purpose of static classes

What is the purpose of making a class static?
public static class December {
}The only reason I can see is to access inner-classes without instantiating the outer-class? Are there any other?

see these
http://forum.java.sun.com/thread.jsp?forum=31&thread=277820
http://forum.java.sun.com/thread.jsp?forum=31&thread=305260

Similar Messages

  • What is the purpose of Static methods inside a class?

    Hi,
    What is the purpose of Static methods inside a class?
    I want the answers apart from "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    My question is what is the exact purpose of a static method ?
    Unlike attributes, a separate copy of instance attributes will be created for each instance of a class where as only one copy of static attributes will be created for all instances.
    Will a separate copy of instance method be created for each instance of a class and only one copy of static methods be create?
    Points will be rewarded for all helpful answers.

    Hi Sharma,
    Static methods is used to access statics attributes of a class. We use static attributes when we want to share the same attribute with all instances of a class, in this case if you chage this attribute through the instance A this change will change will be reflected in instance B, C........etc.
    I think that your question is correct -> a separate copy of instance method will be created for each instance of a class and only one copy of static methods be create ?
    "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    Static Method: call method class=>method.
    Instance Method: call method instance->method.
    Take a look at this wiki pages.
    [https://wiki.sdn.sap.com/wiki/x/o5k]
    [https://wiki.sdn.sap.com/wiki/x/ZtM]
    Best regards.
    Marcelo Ramos

  • Singleton pattern class and static class

    Hi,
    what is difference between the singleton pattern class and static class ?
    in singleton pattern, we declare a static member[which hold one value at a time] ,static method[ which return static member value] and a private constructor[not allow to direct instantiation]. My words are -- as a singleton pattern we implement static class .
    so can we say a singleton pattern is static class it means both are same or is any difference between these two ??

    malcolmmc wrote:
    On several occasions I've had to convert a static (never instanceated) class to a singleton type, for example because I realise I need an instance per thread, or I decide to make a program more modular, with more than one configuration.
    I've never done the opposite.
    So generally I favour the singleton if there any "state" involved, because it's more flexible in unanticipated directions. It also gives extra flexibility when building tests, especially if you program to an interface.Total agreement; if anything it is dead hard to override static method logic with mock code in unit tests (I had to do it by keeping the static methods in place but making them internally use a singleton instance of itself of which the instance variable could be overwritten with a mock implementation for unit testing purposes...).
    'Static classes' and/or methods are great for very simple util functions, but I wouldn't use them for anything other than that.

  • Difference between a static class and singleton

    What is the difference between a static object and a singleton ?
    for example:
    1 )
    public class MyObject {
    static MyObject singleton ;
    public static MyObject getInstance() {
    if (singleton ==null) singleton = new MyObject ();
    return singleton;
    private MyObject () {
    supe();
    public void myMethod() {
    2 )
    public class MyObject {
    private MyObject () {
    supe();
    public static void myMethod() {
    If I need to call the myMethod() , witch of this solution is better ?
    // case 1
    MyObject.getInstance().myMethod()
    // case 2
    MyObject.myMethod()
    .....

    This has been discussed a lot here.
    Use the forum's search feature, or, since it's not necessarily reliable, use google.
    For many intents and purposes, they're equivalent.
    However, with a singleton you can implement an interface, and get polymorphic behavior. You can't do with with a class full of static methods (which, by the way, is NOT a static class).

  • Purpose of debug class and limits in pipelinesession

    Hi
    What is the purpose of debug class(com.bea.p13n.util.debug.Debug)? I found
    it in an InputProcessor. Also I am unable to find the javadocs for it.
    My next question may seem trivial, but is there any limitation to the number
    of attributes that can be set in the pipelinesession object or something like
    that?
    Thanks,
    Raghu

    Hi Raghu,
    I think those are internal java classes used by the portal server. To your next
    question, i am not aware of any limitation on the number of pipeline attributes.
    Regards
    Syed
    "Raghu V.N" <[email protected]> wrote:
    >
    Hi
    What is the purpose of debug class(com.bea.p13n.util.debug.Debug)?
    I found
    it in an InputProcessor. Also I am unable to find the javadocs for it.
    My next question may seem trivial, but is there any limitation
    to the number
    of attributes that can be set in the pipelinesession object or something
    like
    that?
    Thanks,
    Raghu

  • Purpose of Requirement Class

    What is the purpose of requirement class?

    The requirements class contains all control features for planning such as relevance for
    planning, requirements planning strategy and requirements consumption strategy. In
    addition, it is specified at a global level whether an availability check is to take place for
    the material in the sales and distribution documents on the basis of the ATP quantity
    (ATP = available to promise) and whether requirements are to be passed on. A finer
    degree of control can be obtained for sales documents using the schedule line category.
    Replenishment lead time is only included in the check performed on the basis of the
    ATP quantity.
    Also please check this link: http://wiki.sdn.sap.com/wiki/pages/viewpage.action?pageId=29323
    Regards
    Sai

  • Creation of a static class with private methods

    I'm new to java programming and am working on a project where I need to have a static class that does a postage calculation that must contain 2 private methods, one for first class and one for priority mail. I can't seem to figure out how to get the weight into the class to do the calculations or how to call the two private methods so that when one of my other classes calls on this class, it retrieves the correct postage. I've got all my other classes working correct and retrieving the information required. I need to use the weight from another class and return a "double". Help!!!
    Here's my code:
    * <p>Title: Order Control </p>
    * <p>Description: Order Control Calculator using methods and classes</p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: Info 250, sec 001, T/TH 0930</p>
    * @author Peggy Blake
    * @version 1.0, 10/29/02
    import javax.swing.*;
    public class ShippingCalculator
    static double firstClass, priorityMail;
    //how do I get my weight from another class into this method to use??? not sure I understand how it works.
    public static double ShippingCalculator(double weight)
    String responseFirstClass;
    double quantity, shippingCost;
    double totalFirstClass, firstClass, priorityMail, totalShipping;
    double priorityMail1 = 3.50d;//prioritymail fee up to 1 pound
    double priorityMail2 = 3.95d;//prioritymail fee up to 2 pounds
    double priorityMail3 = 5.20d;//prioritymail fee up to 3 pounds
    double priorityMail4 = 6.45d;//prioritymail fee up to 4 pounds
    double priorityMail5 = 7.70d;//prioritymail fee up to 5 pounds
    quantity = 0d;//ititialization of quantity
    // weight = 0d;//initialization of weight
    // shippingCost = 0d;
    //calculation of the number of items ordered..each item weights .75 ounces
    quantity = (weight/.75);
    if (quantity <= 30d)
    //add 1 ounce to quantities that weigh less than 30 ounces
    weight = (weight + 1);
    else
    //add 2 ounces to quantities that weigh more than 30 ounces
    weight = (weight + 2);
    if (weight > 80d)
    //message to orderclerk ..order over 5 lbs, cannot process
    JOptionPane.showMessageDialog(null, "Order exceeded 5 lbs, cannot process");
    //exit system, do not process anything else
    System.exit (0);
    else
    if (weight < 14d)
    //send message to customer: ship firstclass or priority, y or n
    responseFirstClass = JOptionPane.showInputDialog(null, "Ship first class? y or n?");
    if (responseFirstClass.equals("y"))
    //compute FirstClass shipping cost
    totalFirstClass = ((weight - 1) * .23d) + .34d;
    firstClass = totalFirstClass;
    else
    //compute PriorityMail cost for orders less than 14 ounces
    priorityMail = (priorityMail1);
    else
    if (weight <=16d)
    //compute totalshipping for orders up to 16 ounces
    priorityMail = (priorityMail1);
    else
    if (weight <=32d)
    //compute totalshipping for orders up to 32 ounces
    priorityMail = (priorityMail2);
    else
    if (weight <=48d)
    //compute totalshipping for orders up to 48 ounces
    priorityMail = (priorityMail3);
    else
    if (weight <= 64d)
    //compute totalshipping for orders up to 64 ounces
    priorityMail = (priorityMail4);
    else
    //compute totalshipping for orders up to 80 ounces
    priorityMail = (priorityMail5);
    priorityMail = 0d;
    firstClass = 0d;
    firstClassMail ();
    priorityMailCost ();
    //I think this is where I should be pulling the two methods below into my code, but can't figure out how to do it.
    shippingCost = priorityMail + firstClass;
    return (shippingCost);
    }//end method calculate shipping
    private static double firstClassMail()//method to get first class ship cost
    return (firstClass);
    }//end method firstclass shipping
    private static double priorityMailCost()//method to get priority mail cost
    return (priorityMail);
    }//end method priorityMail
    }//end class shipping calculator

    public class A {
    public String getXXX () {
    public class B {
    A a = new A();
    public void init () {
    a.getXXX();
    }

  • Alternative to Static Class Inherit

    Greetings,
    I’ve been using some code for years in a different number of applications but that involves a lot of copy paste and is a nightmare to maintain. For that reason I’ve took some time to re-organize some of my codes and that mainly involves
    splitting it into multiple projects for latter inclusion in a number of solutions.
    So far so good and I’d say 95% is done but I’m now stuck with a Static Class I need to use. I basically need a few “Global” parameters and settings to be available across every solution. I know I can’t Inherit a Static Class nor override
    a Field to return a different value unfortunately.
    In a nutshell:
    myFrameworkProject
    namespace
    myFramework.Classes{
                    //these contains general stuff
    used in every project
                    public static class Globals{
                                   public static
    XPTO veryImportantProperty = new XPTO()
                                   public static
    Settings Settings = new Settings();
    public void doSomethingImportant();
    Public class Settings{
                    Private
    string Username;
                    Private
    string Password;
                    Private
    string Whatever;
    myFancyProject
    namespace
    myFancyProject.Classes{
                    //these add specific stuff used
    in this project
                    public static class Globals : myFramework.Classes.
    Globals {
                                   public static
    override mySettings Settings = new mySettings();
    Public class mySettings: myFramework.Classes .Settings{
                    //some
    more specific settings I need
                    Private
    string SomethingElse;
    What are my options? I’ve been trying to play with Singletons but for some reason I just can’t seem to make it work the way I want to…probably because it’s just not the right way to do it in the first place.

    I think you are over thinking it a little bit. The example you have above would be great if you had multiple setting types you wanted to retrieve within the same application domain instance using keys or specific types. The way I understand your problem
    is you have one settings type per application that you run with various applications sharing a code base. Here is an example I created for you which better illustrates the solution I had in mind when I read your problem.
    There are 2 namespaces, the one for your custom project(s) named FancyProject and then the Core / framework. Hope this helps!
    namespace JF.FancyProject
    using JF.Framework.Classes;
    // in initialization of your default application domain (ie. in your application startup)
    // inject your MySingleton with your custom implementation of ISettingsBuilder
    // this can be done in many ways from hard coding in each startup routine to IoC / Dependency Injection
    // the end result is this
    public static class Console
    public static void Main(params string[] args)
    MySingleton.Initialize(new ConcreteSettingsBuilder());
    // now you can use it where ever
    var temp = MySingleton.SettingsConcreteInstance<ConcreteSettings>().SomethingCustom;
    // or base
    var temp1 = MySingleton.SettingsInstance.SomeBaseThing;
    public sealed class ConcreteSettings : JF.Framework.Classes.SettingsBase
    public string SomethingCustom { get; set; }
    public sealed class ConcreteSettingsBuilder : BaseSettingsBuilder, ISettingsBuilder
    public override SettingsBase CreateSettings()
    var settings = new ConcreteSettings();
    // call the base if you need to get standard settings populated
    base.populateBaseSettings(settings);
    // populate all of your custom settings
    return settings;
    namespace JF.Framework.Classes
    public abstract class SettingsBase
    public string SomeBaseThing { get; set; }
    // base settings and behavior that can be abstracted
    public static class MySingleton
    private static SettingsBase _settings;
    private static Lazy<SettingsBase> _lazyCreationMethod;
    public static void Initialize(ISettingsBuilder builder)
    _lazyCreationMethod = new Lazy<SettingsBase>(builder.CreateSettings);
    public static SettingsBase SettingsInstance
    get { return _lazyCreationMethod.Value; }
    public static T SettingsConcreteInstance<T>() where T : SettingsBase
    return (T) _lazyCreationMethod.Value;
    public abstract class BaseSettingsBuilder : ISettingsBuilder
    public abstract SettingsBase CreateSettings();
    protected virtual void populateBaseSettings(SettingsBase settings)
    // if you find many of your settings are created the same way use a base class
    public interface ISettingsBuilder
    SettingsBase CreateSettings();
    Edit:
    One more thought. I do agree with some of the other posters that  for bigger projects the use of a Singleton pattern is not a good idea. For little applications it does not matter too much because chances are there is not enough substance that it will
    hinder your code and the development cycles are generally very short.
    Should you want to reconsider the Singleton pattern then I recommend you look at something like
    Autofac, you could use this to inject instances of your ISettingsBuilder, or other concrete instances, directly into your dependent classes and you could take it further in developing self containing services that you could
    inject as well.
    Again, for small projects its not a big deal but if you ever start on something a bit more complex its worth looking into.
    -Igor

  • Static Class JMS Listener

    I am designing an EJB component (MessageDrivenBean) that requires
    dynamic ("hot") configuration changes. As such, the bean must be
    notified somehow of configuration changes in the DB (rather than have
    to poll the DB for changes at every method call).
    I'm thinking of implementing this functionality using a static class
    instance (singleton) that is shared between the multiple instances of
    the bean. This static instance would listen on a JMS topic for
    configuration change events and update its internal cache accordingly
    (by getting the configuration information from the DB). The beans
    would then access this in-memory static instance everytime they need
    configuration info instead of polling the database. By using the JMS
    topic, I guarantee that clustered instances of Weblogic will all be
    notified of the database changes (each instance would have its own
    "cache" singleton).
    I'm pretty sure all of this will work, but I'm equally sure that I'm
    violating some EJB rules. Singletons and JMS listeners are generally
    discouraged. Are there any alternatives to this design?

    Hi Joost,
    This all seems to be pretty complicated. Not to mention that you can not
    guarantee that members of a cluster will be notified simultaneously.
    Why don't you want using the database?
    "Joost Ouwerkerk" <[email protected]> wrote in message
    news:[email protected]..
    I am designing an EJB component (MessageDrivenBean) that requires
    dynamic ("hot") configuration changes. As such, the bean must be
    notified somehow of configuration changes in the DB (rather than have
    to poll the DB for changes at every method call).
    I'm thinking of implementing this functionality using a static class
    instance (singleton) that is shared between the multiple instances of
    the bean. This static instance would listen on a JMS topic for
    configuration change events and update its internal cache accordingly
    (by getting the configuration information from the DB). The beans
    would then access this in-memory static instance everytime they need
    configuration info instead of polling the database. By using the JMS
    topic, I guarantee that clustered instances of Weblogic will all be
    notified of the database changes (each instance would have its own
    "cache" singleton).
    I'm pretty sure all of this will work, but I'm equally sure that I'm
    violating some EJB rules. Singletons and JMS listeners are generally
    discouraged. Are there any alternatives to this design?Regards,
    Slava Imeshev

  • Do static classes persist for the lifetime of the applet or the JRE in 1.4

    I have an application that runs in a web browser and uses several applets that share data between each other using a static class. This method works fine for version 1.3 but not in 1.4.x. Do static classes now only exist for the lifetime of the applet?

    I had a similar problem and solved it by setting the codebase attribute on the applet tags. The only documentation I have been able to find about this issue is here: http://java.sun.com/products/plugin/1.3.1_01a/new.html#classloader

  • Usage of non static members in a static class

    Can you explain the usage of nonstatic members in a static class?

    Skydev2u wrote:
    I just recently started learning Java so I probably know less than you do. But from what I've learned so far a static class is a class that you can only have one instance of, like the main method. As far as non static members in a static class I think it allows the user to modify some content of the class(variables) even though the class is static. A quick Google help should help though.Actually the idea behind a static class is that you dont have any instances of it at all, its more of a place holder for things that dont have anywhere to live.
    Non-static members in a static class wouldnt have much use

  • Attributes of private static class - private or package private?

    Consider the following code:
    public class Outer {
        // Remainder omitted
        private static class Nested {
            int someInt           = 10;
            String someString = "abc";
    }The nested class Nested is declared private, as it is only used by the Outer class... now I wonder... should I declare Nested's attributes private oder package private... either way, they can't be accessed from the outside... any ideas?

    stevops wrote:
    either way, they can't be accessed from the outsideThat is true. However, when in addition the members of class Nested are declared as private, you will not be able to access them also from within the class Outer as well, i.e. int i = Nested.someInt; will give you compliation errorsAs a matter of fact, at most it'll generate some warnings, for it (the compiler) will generate synthetic accessor methods for Nested's fields.
    All in all, if you plan to access private class members from an enclosing (or inner) class, you really only have two options: make them explicitly package-private, or make them implicitly so.

  • Releasing static classes in a browser environment

    Hi all, got a problem I can't seem to find a solution for, so hoping someone knows what to do with this!
    I'm running a Java applet in a browser, under Sun's JVM. It has a custom dynamic class loader, which queries our server and downloads patches to the software. However, this doesn't work entirely as planned. The JVM doesn't seem to want to clear the class cache until the browser is restarted. I'm also wondering about static class definitions and whether I'd have to do something different to refresh those too.
    Ideally, when the loader starts and downloads patches to files, it then completely wipes out its previous definitions of cached classes, and reloads them all again from disk. Is this possible, and how would I go about doing it?
    (The reason for this behaviour is my old old software ran on Java 1.1, and the MS Java plugin exhibits this behaviour, which our users were used to...)
    Thanks in advance!
    David

    Thanks for the quick reply :)
    The loader is not static, so it should be using a new
    instance each time already? Or is it not sufficient
    to simply make it not static?Not really sure how to answer that! It's not static, so presumably it's an instance field of some other class. Now, are you using a new instance of that object each time you download a new patch? If not, that'll probably be the problem. If so, then probably what's going on is, your classloader isn't loading the classes at all, but simply delegating to it's parent. If that's the case, you need to make that delegation fail, for example by not giving your classloader a parent

  • Can we create static class in actionscript 3.0

    Hi If yes please send me chunk of code .
    thanks

    Hi Prashanth,
    There is no specifically a Static class in Flex that you can declare it at the compile time. However you can have Static variables and methods in your class and you can call them using the class name itself without creating an instance of that class.
    Here is the chunk of code...
    package com.constants
    [Bindable]
    public class ConsumerMessageConstants
      public static const UNABLE_TO_ENROLL_PLANS_MESSAGE_ID:String = "10000";
      public static const MARITAL_STATUS_UPDATED_MESSAGE_ID:String = "10001";
      public static const ERROR_IN_EDITING_MARITALSTAUS_MESSAGE_ID:String = "10002";
      public static const SMOKER_STATUS_SAVED_SUCCESSFULLY_MESSAGE_ID:String = "10003";
      public static const PASSWORD_RESET_REQUIRED_MESSAGE_ID:String = "10004";
      public static const ADDRESS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10005";
      public static const UNABLE_TO_REMOVE_THIS_DEPENDENT_MESSAGE_ID:String = "10006";
      public static const EMPLOYEE_SALARY_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10007";
      public static const ERROR_IN_EDITING_SALARY_MESSAGE_ID:String = "10008";
      public static const PLEASE_SELECT_A_CONSIDER_PLAN_MESSAGE_ID:String = "10009";
      public static const YOU_MUST_CHOOSE_A_PLAN_COVERAGE_LEVEL_MESSAGE_ID:String = "10010";
      public static const PLEASE_SELECT_PLAN_TO_LOCK_PORTFOLIO_MESSAGE_ID:String = "10011";
      public static const DEEPDIVE_INFORMATION_SAVED_SUCCESSFULLY_MESSAGE_ID:String = "10012";
      public static const NO_DATA_TO_DISPLAY_MESSAGE_ID:String = "10013";
      public static const NO_PLANS_AVAILABLE_TO_ENROLL_MESSAGE_ID:String = "10014";
      public static const NO_PLANS_TO_BE_ENROLLED_MESSAGE_ID:String = "10015";
      public static const PASSWORD_CHANGED_SUCCESSFULLY_MESSAGE_ID:String = "10016";
      public static const NEW_PASSWORD_AND_CONFIRM_PASSWORD_SAME_MESSAGE_ID:String = "10017";
      public static const YOUR_DATA_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10018";
      public static const HEALTH_PLAN_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10019";
      public static const HEALTH_PLAN_IS_ADDED_SUCCESSFULLY_MESSAGE_ID:String = "10020";
      public static const MONEY_PLAN_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10021";
      public static const MONEY_PLAN_IS_ADDED_SUCCESSFULLY_MESSAGE_ID:String = "10022";
      public static const PROTECTION_PLAN_IS_UPDATED_SUCCESSFULLY_MESSAGE_ID:String = "10023";
      public static const PROTECTION_PLAN_IS_ADDED_SUCCESSFULLY_MESSAGE_ID:String = "10024";
      public static const UNABLE_TO_RETRIEVE_PATHS_MESSAGE_ID:String = "10025";
      public static function func1():Void
      public static function func2():Void
      public function ConsumerMessageConstants()

  • Static class garbage collection

    Can garbage collector can garbage collect static classes ?.
    My doubt is that when you access a static class , that class is loaded through its class loader ( when first time that class is referenced ).
    So when did the garbage collector collects this static class ( assume that static class no longer referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a particular class ( Assume that i m implementing a singleton for my java runtime)
    thanks and regards
    Renjith.

    Can garbage collector can garbage collect static classes ?. Static classes are nothing special in terms of class loading - they are only different in visibility for linking.
    Perhaps you mean static members of classes?
    My doubt is that when you access a static class ,
    that class is loaded through its class loader ( when
    first time that class is referenced ). Classes are always loaded through classloaders. Objects of those classes are allocated from the heap, and the object instances refer to the class object.
    Objects (either instances, or classes themselves) are garbage collected when they are no longer live (i.e. no live object refers to them). (This is a somewhat recursive definition, and sometimes, you can have cyclic dependencies that make garbage collection tricky, but the GC, while it has to be conservative for correctness, usually gets it right).
    So for a static member to be garbage-collected, the class has to be garbage-collected first. The class cannot be GC'ed until all references to it go away (this includes all dynamically allocated objects of that type, and the class loader that loaded that class).
    And yes, class loaders can go away, but only if they are created by your program. The system class loader (which is the default classloader you get if you don't create any class loaders of your own) never goes away, so any class loaded from CLASSPATH will never be unloaded.
    (As an example, servlet containers - e.g. Tomcat, Weblogic, etc.) allocate one or more classloaders for each webapp. When the webapp is un-deployed, the classloaders are "orphaned", and they, and any classes loaded by them (from the WEB-INF/lib and WEB-INF/classes directories) are unloaded and garbage-collected. (After all the dynamic objects of those classes are GC'ed, of course).
    >
    So when did the garbage collector collects this
    static class ( assume that static class no longer
    referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a
    particular class ( Assume that i m implementing a
    singleton for my java runtime)
    thanks and regards
    Renjith.

Maybe you are looking for