Do Static Classes exist?

Does Java allow the creation of static classes, and if so does that mean an instance of the class cannot be created? I know that a class can have static methods that only access static instance variables, but I don't know if that means that the class itself is static. I ask because I realized that you can't declare a static class like "public static class A {...}"

@OP. An inner class can be declared to be static,but
top level classes can't be static.
But that doesn't mean the static inner class
can't be instantiated (which seems to be what the OP
is thinking of).That was an answer to the topic - "Do static classes exist?", and the question does also say:
"Does Java allow the creation of static classes, and if so does that mean an instance of the class cannot be created?"
So I thought that the OP also wanted to know if static classes existed.
Kaj

Similar Messages

  • 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

  • Static class

    Hello
    at the start of my programme I would like to store some valuse (the values are trhe user rights that will be read from the data base) these values will never change during the execution of the programme.
    so I was told that the best is to create a static class ...
    can any one post an example of static class and how to store the values inside
    and how to read it back
    or just any link that speak about this
    thank you in advance.

    yeah i understand the ?:;
    my question was on the form of the newthe code checks to see if an instance of Example already exists, and if it does, it returns that. if not, it creates a new one first. theoretically, only one instance will ever exist, but in practice, this variant of the pattern isn't thread-safe. simplest singleton:
    public class MySingleton {
      private static MySingleton INSTANCE = new MySingleton();
      private MySingleton() {}
      public static MySingleton getInstance() {
        return INSTANCE;
    }still lazily-loaded, despite what people might tell you, since the class itself is only loaded when you first need it

  • Static Classes/Methods vs Objects/Instance Classes/Methods?

    Hi,
    I am reading "Official ABAP Programming Guidelines" book. And I saw the rule:
    Rule 5.3: Do Not Use Static Classes
    Preferably use objects instead of static classes. If you don't want to have a multiple instantiation, you can use singletons.
    I needed to create a global class and some methods under that. And there is no any object-oriented design idea exists. Instead of creating a function group/modules, I have decided to create a global class (even is a abstract class) and some static methods.So I directly use these static methods by using zcl_class=>method().
    But the rule above says "Don't use static classes/methods, always use instance methods if even there is no object-oriented design".
    The book listed several reasons, one for example
    1-) Static classes are implicitly loaded first time they are used, and the corresponding static constructor -of available- is executed. They remain in the memory as long as the current internal session exists. Therefore, if you use static classes, you cannot actually control the time of initialization and have no option to release the memory.
    So if I use a static class/method in a subroutine, it will be loaded into memory and it will stay in the memory till I close the program.
    But if I use instance class/method, I can CREATE OBJECT lo_object TYPE REF TO zcl_class then use method lo_object->method(), then I can FREE  lo_object to delete from the memory. Is my understanding correct?
    Any idea? What do you prefer Static Class OR Object/Instance Class?
    Thanks in advance.
    Tuncay

    @Naimesh Patel
    So you recommend to use instance class/methods even though method logic is just self-executable. Right?
    <h3>Example:</h3>
    <h4>Instance option</h4>
    CLASS zcl_class DEFINITION.
      METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    <h4>Static option</h4>
    CLASS zcl_class DEFINITION.
      CLASS-METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      CLASS-METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
    zcl_class=>add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
    zcl_class=>subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    So which option is best? Pros and Cons?

  • Are private fields public in a static class?

    If a variable in a static class is declared as private, it still seems to be visible. Are access specifiers without any importance in a static class?

    Roxxor wrote:
    tschodt wrote:
    The outer class can access all the fields of the nested class, yes.Yes, but only if the nested class is static, otherwise not.
    This is what I have noticed:
    If the nested class is not static, then the outer class has to instantiate the nested class to access its variables. Well, not really. If the nested class is not static (i.e., it's a nested class), then its variables don't even exist until an instance is created.
    If the nested class is not static, then the nested class can access the outer class´ variables without instantiate it. The inner class can only exist if there exists an instance of the outer class. An inner class (a non-static nested class) contains a reference to the wrapping class. So, it doesn't have to instantiate the outer class, because an instance already exists.
    If the nested class is static, then the nested class has to instantiate the outer class to access its variables. I guess. It seems like a really strange design though.

  • Static class error

    I have a static class:
    package VO
        public class ArrayValues
            private static var instance:ArrayValues = new ArrayValues();
            // dummy values will be first replaced with English versions
            // if the user clicks "Spanish" they will be replaced with that
            private var yesNoArray:Array = new Array('1','2');
            private var utilityArray:Array = new Array('1','2');
            public function ArrayValues()
                throw Error("ArrayValues is called by its instance");
            public static function getInstance():ArrayValues
                return instance;
            public function getYesNoArray():Array
                return yesNoArray;
            public function setYesNoArray(input:Array):void
                yesNoArray = input;
    It is invoked here:
            import VO.ArrayValues;
            import VO.InputData;
            import VO.InputLabels;
            [Bindable]
            public var saveData:InputData = InputData.getInstance();
            [Bindable]
    168       public var getArrays:ArrayValues = ArrayValues.getInstance();
    It produces this error:
    Error: ArrayValues is called by its instance
        at VO::ArrayValues()[C:\FSCalc\Flex\FSCalc\src\VO\ArrayValues.as:14]
        at VO::ArrayValues$cinit()
        at global$init()[C:\FSCalc\Flex\FSCalc\src\VO\ArrayValues.as:3]
        at components::InputForm()[C:\FSCalc\Flex\FSCalc\src\components\InputForm.mxml:168]
        at FSCalc/_FSCalc_InputForm1_i()
        at FSCalc/_FSCalc_Array6_c()
    What am I doing wrong?
    PS, is it normal to take almost 10 minutes to a) go to your discussions, b) read one response to one thread and c) get back to the normal discussion?  That seems excessive to me.

    Sorry for the late reply.  I've just got back to this project after the usual "an emergency" stuff.
    Yes, I'm looking to create a singleton.  I want to pass values around without having to have monster long parameter lists for the various components.
    I based the Flex I have on a web page and noted it is similar to the java idea, but not identical based on that page.
    I want to make sure I understand the theory behind the code.
    public function ArrayValues(access:SingletonEnforcer)
         if ( access == null )
              throw Error("ArrayValues is called by its instance");
    This is the constructor for the class which has the same name as the file it is in.  A parameter is passed of the type "SingletonEnforcer" and is then tested to see if it were ever invoked.  If it were, an error is created with a string which will be written to the console.
    Next, a variable local to this class is created that will be of the type "ArrayValues" to hold the various arrays.  BTW, either this will have to be expanded or a parallel class created to hold the Spanish values.
    static private var _instance  :  ArrayValues;
    Next, the actual work horse and true "constructor" is made.  This will either allocate a new instance of the class if it doesn't already exist or instantiate it if it doesn't.  I am confused by the second class, however, when it is created the first time.  This class is included in this file?  Doesn't the file name have to match the class?

  • Lifetime of static classes in WebDynpro

    Hi,
    I have a question regarding static java classes in WebDynpro: Does anybody know details about their lifetime. I was searching for this information but I didn't find info.
    The background of this question is, that I would like to store configuration data (customizing) from the R/3 in a static class of my WebDynpro application, in order to minimize DB requests. Exists a static class for the whole WebDynpro session or is it destroyed after every user interaction?
    Thanks in advance,
    Martin

    Hi
    If  I have understood you
             You  want to create a static class,  you are expecting the values will remain same for the lifetime of the
    webdynpro app.
    In order to understand the use of the static keyword in class declaration, we need to understand the class
    declaration itself. You can declare two kinds of classes: top-level classes and inner classes.
    Top-level classes
    You declare a top-level class at the top level as a member of a package. Each top-level class corresponds to
    its own java file sporting the same name as the class name.
    A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do
    so. The compiler will detect and report this error.
    you cant write a code like
    public static class hello {
    it gives an error like
    Illegal modifier for the class hello; only public, abstract & final are permitted
    Regards
    Abhijith YS

  • Identity(Prebably using FM) whether a class exists in a system or not?

    Hi,
    I want to check whether a class exists in a system or not in my program.
    How can I do that?
    There is a function module FUNCTION_EXISTS which tells whether a function module exists or not.
    Similar one if existing for a class if any would help.
    Regards,
    Bikash.

    Hello Bikash
    I would use static method CL_OO_CLASS=>GET_INSTANCE (alternative: CL_OO_OBJECT).
    If this method cannot get an instance of the class then the class does not exist.
    Corresponding fm is: SEO_CLASS_GET
    For interfaces you may use: CL_OO_INTERFACE of SEO_CLIF_GET
    Regards
      Uwe

  • Difference between static class and singleton?

    Hi I wonder what could be the difference between static methods and singleton?
    In singleton at any point of time there will be only one object existing in the JVM. We create singleton to avoid multiple object creation for that class.
    If I make all the methods in the class as static also it does the same job. The memory will be allocated once. Even there wont be any object in this case, so time required for object creation also can be saved. looks like more efficient but still why need singleton?
    This question is also posted in java programming forum. The thread is as follows:-
    [Click on this to visit that thread |http://forum.java.sun.com/thread.jspa?threadID=5278517&tstart=0]
    Edited by: murrayb9654 on Mar 25, 2008 8:20 AM

    yawmark wrote:
    Static class is a realization of singleton pattern.Not in any conventional sense.
    ~Especially since a static class is completely different from a class with all static methods.

  • Determine if Instance of Class exists?

    Hello out there :)
    could anyone tell me if there is a way to determine if an instance of a specific class exists.
    btw my class design does not allow me to use static variables for instance counter or somehting - i am trying to prevent this.
    here is my situation:
    I have a class in which's constructor i would like to check if an instance of an inherited class exists - of THE inheritet class, that this constructor was called from (i could pass this information via constructor)
    and now i only want the constructor to proceed, if there is no instance of this class yet.
    thx to everyone who can help me :)

    mlk wrote:
    Imagist wrote:
    Let's see, your root class would be:
    public class ClassXY
         private static boolean instanceExists = false;
         public ClassXY() { instanceExists = true; }
         final public static boolean instanceExists() { return instanceExists; }
    When a object gets GC'ed, should that still return exists? :)Ah! You're right! So the code would be:
    public class ClassXY
         private static boolean instanceCount = 0;
         public ClassXY() { instanceCount++; }
         final public static boolean instanceExists() { return instanceCount > 0; }
         protected void finalize() { instanceCount--; }
    }There might be a threading issue with that, too; it's been a while since I dealt with finalization.
    One question for the original poster: do you want the constructor to fail if an instance already exists? If that's the case, the code above can be simplified further.

  • 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

  • Service "No valuation class exists for account reference"

    Hi,
    in AC01 trx, I cannot create a Service.
    The error is:
    No valuation class exists for account reference
    I tried with trx OMSK to link the account category reference to material type but won't work.
    The error is always: No valuation class exists for account reference

    Hi,
    try also to check from SPRO, Materials Management, External Services Management, Service Master, "Define Service Category", you have to set the standard "Account category reference" 0006 or the one (custom) you have set in customizing also check (Valuation and Account Assignment trx OMSK)
    Regards

  • 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

Maybe you are looking for

  • How to change the default operators in sap web ui Search screen?

    How to change the default operators in sap web ui Search screen? For eg. Using advance search option , I have some fields with default operators like equals, contains,is between, is less than and is greater than. I don't need all these operators for

  • IE unable to connect to Oracle HTTP Server v10.1.2 with SSL

    Hi, I configured OHS with SSL to run APEX applications. This configuration can be run from Mozilla browsers and Opera, but not from Internet Explorer. I suspect that IE doesn't support 256-bit encryption, as both browser above support it. So I set se

  • Root partition filling up over time

    I am running Sol 10 11/06 on a Sun Blade. I installed Sol 10 from DVD a few months ago, making my / partition 12GB in size. /var is not a separate partition. Sun Studio 11 was also installed. I have installed all available patches using Sun Update Ma

  • Download Z*Objects

    Hello All, Is there any standard report in SAP that downloads all the Z Custom objects/reports along with the Titles of these objects or the method of going to TRDIRT and D010SINF to get the Zobject name, title and the Program Type. Do let me know th

  • Archive PDF file into ECC

    Hi Friends, I have a requirement, Archiving PDF file into ECC. Could you please let me know the process. Regards, Nivas. Moderator message: please do some research before posting. Edited by: Thomas Zloch on Jan 24, 2012