Static data & methods

I'm new to java programming and I'm having a really big problem with the use of and implementation of static data types and methods- help me out!!!

When do you choose to declare a variable to be static
and not
private or public?They aren't mutually exclusive. You can have public static variables.
Are static data members associated only with a
specific instance of the
declared class??Static members are part of the class not of a specific instance.
You described instance variables.
Can non-static methods access declared static data
types??Yes, but the opposite is not true.
can you use the "this" keyword in both static and
instance methods ??No, in static methods there is no "this" which refers to the current object (which doesn't exist in static context).
Can you declare your static data members as "Public"??Yes.

Similar Messages

  • Does not contain a static 'Main' method suitable for an entry point_

    Hello
    I want to to do a project with Entiity Framework . I add a project to my solution for my domain class and it's name is 'LinkModel.DomainClasses'.  when I prees F5 there is an error like bellow.
    Could You help me to solve this? thanks alot
    ..\Documents\Training\LinkCodeFirstLast\LinkCodeFirst\LinkCodeFirst\LinkModel.DomainClasses\obj\Debug\LinkModel.DomainClasses.exe'
    does not contain a static 'Main' method suitable for an entry point

    Hi bkshn,
    This error is caused by the missing "Main" method in your project. it is the entry point of your project.
    If you want to create a EF project, you could follow the way in the aricle below.
    https://msdn.microsoft.com/en-us/data/ee712907#codefirst
    The Main method is like below.
    class Program
    static void Main(string[] args)
    using (var db = new BloggingContext())
    // Create and save a new Blog
    Console.Write("Enter a name for a new Blog: ");
    var name = Console.ReadLine();
    var blog = new Blog { Name = name };
    db.Blogs.Add(blog);
    db.SaveChanges();
    // Display all Blogs from the database
    var query = from b in db.Blogs
    orderby b.Name
    select b;
    Console.WriteLine("All blogs in the database:");
    foreach (var item in query)
    Console.WriteLine(item.Name);
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
    And you could start to learn the EF from the following MSDN blogs.
    https://msdn.microsoft.com/en-us/data/ee712907
    If you have any other concern regarding this issue, please feel free to let me know.
    Best regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Creation of a table with static data(not a DB table)

    Hi
    I need to display a table with some static data in an OAF page. This table is not a DB table. It is like an HTML table
    I have placed the following query
    SELECT 'A1','B1' FROM DUAL UNION SELECT 'A2',B2' FROM DUAL in the VO. But it is returning a single row which is acting as the header of the table.
    Can anyone help me to create the table with 2 rows inserted in it.
    Thanks
    Edited by: gsaxena on Aug 4, 2009 3:04 AM
    Edited by: gsaxena on Aug 4, 2009 5:24 AM

    Hi
    Please execute your VO inside the CO of table region ,right now it is not getting executed,thats y it is giving just column names
    use the following code PR method of CO
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    OAViewObject oav = (OAViewObject)am.findViewObject("XXVO");
    oav.first();
    let me know in case of any issue
    thanx
    Pratap

  • How to synchronize concurrent access to static data in ABAP Objects

    Hi,
    1) First of all I mwould like to know the scope of static (class-data) data of an ABAP Objects Class: If changing a static data variable is that change visible to all concurrent processes in the same Application Server?
    2) If that is the case. How can concurrent access to such data (that can be shared between many processes) be controlled. In C one could use semaphores and in Java Synchronized methods and the monitor concept. But what controls are available in ABAP for controlling concurrent access to in-memory data?
    Many thanks for your help!
    Regards,
    Christian

    Hello Christian
    Here is an example that shows that the static attributes of a class are not shared between two reports that are linked via SUBMIT statement.
    *& Report  ZUS_SDN_OO_STATIC_ATTRIBUTES
    REPORT  zus_sdn_oo_static_attributes.
    DATA:
      gt_list        TYPE STANDARD TABLE OF abaplist,
      go_static      TYPE REF TO zcl_sdn_static_attributes.
    <i>* CONSTRUCTOR method of class ZCL_SDN_STATIC_ATTRIBUTES:
    **METHOD constructor.
    *** define local data
    **  DATA:
    **    ld_msg    TYPE bapi_msg.
    **  ADD id_count TO md_count.
    **ENDMETHOD.
    * Static public attribute MD_COUNT (type i), initial value = 1</i>
    PARAMETERS:
      p_called(1)  TYPE c  DEFAULT ' ' NO-DISPLAY.
    START-OF-SELECTION.
    <b>* Initial state of static attribute:
    *    zcl_sdn_static_attributes=>md_count = 0</b>
      syst-index = 0.
      WRITE: / syst-index, '. object: static counter=',
               zcl_sdn_static_attributes=>md_count.
      DO 5 TIMES.
    <b>*   Every time sy-index is added to md_count</b>
        CREATE OBJECT go_static
          EXPORTING
            id_count = syst-index.
        WRITE: / syst-index, '. object: static counter=',
                 zcl_sdn_static_attributes=>md_count.
    <b>*   After the 3rd round we start the report again (via SUBMIT)
    *   and return the result via list memory.
    *   If the value of the static attribute is not reset we would
    *   start with initial value of md_count = 7 (1+1+2+3).</b>
        IF ( p_called = ' '  AND
             syst-index = 3 ).
          SUBMIT zus_sdn_oo_static_attributes EXPORTING LIST TO MEMORY
            WITH p_called = 'X'
          AND RETURN.
          CALL FUNCTION 'LIST_FROM_MEMORY'
            TABLES
              listobject = gt_list
            EXCEPTIONS
              not_found  = 1
              OTHERS     = 2.
          IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.
          CALL FUNCTION 'DISPLAY_LIST'
    *       EXPORTING
    *         FULLSCREEN                  =
    *         CALLER_HANDLES_EVENTS       =
    *         STARTING_X                  = 10
    *         STARTING_Y                  = 10
    *         ENDING_X                    = 60
    *         ENDING_Y                    = 20
    *       IMPORTING
    *         USER_COMMAND                =
            TABLES
              listobject                  = gt_list
            EXCEPTIONS
              empty_list                  = 1
              OTHERS                      = 2.
          IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.
        ENDIF.
      ENDDO.
    <b>* Result: in the 2nd run of the report (via SUBMIT) we get
    *         the same values for the static counter.</b>
    END-OF-SELECTION.
    Regards
      Uwe

  • How To Create Table with Static Data

    JDEV 10.1.3
    ADF BC
    ADF Faces
    I am trying to make some simple screen/screenflow diagrams to help flesh out some requirements. To do that, I need to make a table with static data that is not hooked up to a data source (because the data model has not yet been clearly defined, and I'm using the diagrams to help iterate the requirements).
    Is it possible to create a table that shows static data (i.e. a set of rows that does not come from a model data source, but rather is hardcoded.)
    If not, how does one create mock ups without actually implementing the data model?
    Thank you.

    Deepak, what specifically in those 2 links from Amis are useful? Those 2 posts are about bind variables, not static list of values?
    In response to the original poster, I'll attempt to help a little more.
    In the 11g release you can create VOs based on a static list of values. However in your case on 10.1.3, the best method I've found is to create a VO based on a SELECT <columns> FROM DUAL statement. The columns then include your dummy data. If you need more than one row, simply UNION ALL a number of SELECT statements together.
    What I haven't checked, is when you eventually transform the VO based on the SELECT DUAL statement into a VO based on an EO drawing real data from the database, is it an easy process? I recommend you try this out before committing to the approach above. Let us know how you go.
    Regards,
    CM.

  • Apply static method requirements on class (Static interface methods)?

    I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
    I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
    What I was hoping to do was something like this>>>
         public interface MyClasses{
              static MyClasses createInstance(byte[] data);
         HashMap<Integer, MyClasses> map;
         public void init() {
              map = new HashMap<Integer, MyClasses>();
              map.put(Class1.getId(), Class1.class);
              map.put(Class2.getId(), Class2.class);
         public void createInstance (int id, byte[] data) {
              map.get(id).createInstance(data);
         }Is there some way I could do this?

    What about something like this?
    public interface Initializable
         public void initialize(byte[] data);
    public class Factory
         private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
            public void registerClass(int id, Class klass)
                    if (! Initializable.class.isAssignableFrom(klass))
                             // you may also want to ensure the class declares a parameterless constructor
                             throw new IllegalArgumentException("duff class");
                    if (this.map.keySet().contains(id))
                             throw new IllegalArgumentException("duff id");
              this.map.put(id, klass);
         public Initializable createInstance(int id, byte[] data)
                    // need some exception handling of course
              Initializable i = map.get(id).newInstance();
                    i.initialize(data);
                    return i;
    }

  • MVC Separation: Static POJO Methods as Controller

    Hi All.
    I am designing my first Java EE app. It is a web-only/no-EJB app but I still want to clearly separate view code and controller code within my web container.
    I am thinking to do this by making a "ViewServlet" class and a "ControllerPOJO" class. The ViewServlet will just pass requests on to the ControllerPOJO and format the returned, processed data to send it back to the client. The ControllerPOJO will have no member data, just static methods like ControllerPOJO.processRequest( ) or something.
    My questions are:
    As I understand it the servlet connection/thread pool is managed by the web container, but POJO threading is not specially managed. In the design I described will the static ControllerPOJO method just execute in the thread of the ViewServlet instance that calls it, the same as if all the code was in the servlet class, or could the threading/connection throughput act differently somehow?
    Is this design orthodox? Maybe what I actually want is a ControllerServlet and a ViewPOJO? Or two servlets, ControllerServlet and ViewServlet?
    Thanks,
    Bishop

    will the static ControllerPOJO method just execute in the thread of the ViewServlet instance that calls it, the same as if all the code was in the servlet class, or could the threading/connection throughput act differently somehow?The general principles of Java Concurrency hold true for Java Servlet as well. Unless a new thread is created to execute the Callee method, both of them will execute in same thread.
    Is this design orthodox? Maybe what I actually want is a ControllerServlet and a ViewPOJO? Or two servlets, ControllerServlet and ViewServlet?Use a controller Servlet for request processing and selecting views. The controller Servlet receives the requests from the client and maps them to an appropriate business model. Based on the results of the operation and state of the model, the controller then selects the next view to display. Finally, the controller generates the selected view and transmits it to the client for presentation. Please check this link for details
    [http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier5.html|http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier5.html]

  • Synchronizing methods and a static main method

    I have a class with a static main method, calling 3 different jdbc updates.
    I want to make sure this is thread safe when called for various clients.
    It's goes:
    args[0] = clientI
    update 1:update field1 where clientid = client1
    update 2:update field2 where clientid = client1
    update 3:update field3 where clientid = client1I assume I am in jeopardy of mixing up my data?
    I don't think I can synchronize a main method, nor would it do any good to synchronize the class?
    Should I break the updates into methods, then synchronize them, or synchronize parts of the code?
    you opinion would help greatly.

    You haven't provided enough information.
    Are those updates occurring sequentially? Then it's threadsafe.
    Are they running in different threads? Then to make them threadsafe you'll need proper synchronization, or a database transaction.
    Of course, looking at those particular updates, I don't see any reason why you'd need to worry about thread safety. They look to be independent of each other. Or perhaps you meant you need them to be atomic? That is, any query will see either the old values of all three fields, or the new values of all three fields. Nobody will be able to see the new values for fields 1 and 2, but the old value for field 3. If that's the case, then those three updates need to be in a database transaction.

  • [svn:osmf:] 10996: Changing MediaElementLayoutTarget to be constructed via a static ' getInstance' method, instead of by its constructor.

    Revision: 10996
    Author:   [email protected]
    Date:     2009-10-19 07:45:26 -0700 (Mon, 19 Oct 2009)
    Log Message:
    Changing MediaElementLayoutTarget to be constructed via a static 'getInstance' method, instead of by its constructor. This prevents the construction of multiple instances that reference one single media-element. Updating client code accordingly.
    Extending layout unit tests. Adding a custom renderer, checking calculation and layout passes invokation counts.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/composition/CompositeViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/composition/ParallelViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/composition/SerialViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/gateways/RegionSprite.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/DefaultLayoutRenderer.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/LayoutContextSprite.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/LayoutRendererBase.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/MediaElementLayoutTarget.as
        osmf/trunk/framework/MediaFramework/org/osmf/utils/MediaFrameworkStrings.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/composition/TestParallelViewableTrai t.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/gateways/TestRegionSprite.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestDefaultLayoutRenderer.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestLayoutUtils.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestMediaElementLayoutTarget. as
    Added Paths:
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/composition/CustomRenderer.as

    AlexCox, can you clarify that once you get the default model out and save it in the temp var, that your ONLY access to the data is then through temp and never through the JList methods?
    Quick question for everyone: Are any of you using JList.setListData to set you initial dataset? I think that is where the bug lies. When I do not use it and start with an empty list, I am able to add to that list, and then remove from that list using the following line:
    ((DefaultListModel)myList.getModel).remove(###);
    And this cast works everytime.
    But when I start that list out with some data such as:
    myList.setListData(myStringArray);
    and then try to execute the above line, boom! I get the ClassCast exception.
    I think setListData creates a whole new model which is an inner class to JList (which seems stupid when DefaultListModel seems made for this).
    Just my thoughts on where the problem lies. I'll add my data directly to the list and see if that works better.
    PK

  • How to garantee that static data is initialized ?

    Hi,
    In order to implement the Prototype design pattern in Java I would like to automatically register the subclasses of Prototype to a static array of prototypes in the Prototype class.
    In C++ I use a static member in each subclass which is initialized by a static method which registers a prototype in the array of prototypes.
    It works in C++ because static data are initialized before main() is called.
    In Java though, to guarantee that static data is initialized it seems that each subclass needs to be loaded first which defeats the idea of automatic registration.
    Another solution to avoid mentionning subclasses names in the Prototype class would be to rely on the relfection API to get all its subclasses but I did not find any method to do that.
    Any hint ?
    Thanks in advance

    It depends what you call a key. In database systems a
    key is part of the data you are looking for.
    In order to get a specific prototype one of course
    needs information.
    Do we disagree here ?If you read the Prototype design pattern you will understand what I mean by key.
    The objective of the Prototype pattern is to decouple
    client code from which classes implement (or subclass)
    the Prototype interface (or abstract class).
    I disagree. It is a creational pattern. The intent of the Prototype pattern is to create a prototypical instance and create new objects by copying the prototype. The intent is not to decouple client code.
    Let's get back to my original question : is there a
    way in Java to register a class automatically to the
    collection of prototypes ?
    Using the reflection API gives an alternative solution
    (thanks to schapel).And I restate my orignal solution as my answer. Why would you want look through all or your classes to determine which ones where prototypes (sorry schapel)?
    If you have a known number of prototype subclasses then you can create and intialize them when the Prototype class is loaded.
    If not then you can use the key to determine if the prototype has been loaded, if not then the Prototype class can load the class. In this case, with some creativitity, you can create a key that meets your needs.
    It seems that you are dependent on the Prototype class containing all of the prototype classes at load time because you are using them to create user interface components. So your client (use interface) is directly coupled to your implementation of the Prototype, exactly what you said the Prototype design pattern incorrectly was intended to do.

  • Static data watermark

    hi to all of you
    Does anyone know something about static data watermarks. Any information could be helpful
    Thanks in advance
    Maddy

    not sure whether I understood you question correctly:
    anyway, (maybe it will help)
    if you declare some data (or even a method) as static, it basically means that it exists once for the whole class. You access it via a reference to class - as opposite to instance variables or methods, which are accessed thru a reference to an instance.
    Note that for static (or "class") variables/methods no instance need to exist at all!class cl1 {
      public static int x = 0;
      public int y = 1;
    int xx = cl1.x;
    cl1 instance = new cl1();
    int yy = instance.y;

  • Static data members

    i am trying to change static data members that are in one class in another class.
    so i have to keep making statements like
    classname.datamembername.method()
    i have to keeping calling classname. a lot of times, is it possible to do it without?
    maybe a bit like passing addresses in c++?
    thanks in adavnce,
    T-fox

    Would i not need to do it like this instead?
    Object obj1=classname.datamembername;
    obj1.method();because after you have created obj1, you dont use it?
    thanks anyone in advance.
    T-fox
    The below statement does the same job as of address
    passing
    Object obj1=classname.datamembername;
    datamembername.method();Bye for now
    CSJakharia

  • Static data and multiple CPUs

    Hi, could anyone explain how data in static data (like static classes, static members of a class etc.) are handled across multiple CPUs in a multi-threaded application?
    Thanks,
    Lei

    nope
    its got way too much to do with the JVM and OS
    thread scheduling and optimisation (particularly in multiple CPU is a nightmare)
    it would also (if the optimisation went that far) depend on the architecture of the CPU in question..
    Althon MP each have processor cache (no surprise i guess) but the clever bit is that there is a very high speed buss to share the cache
    so in that case (i would guess) that one CPU could handle the static methods for a particular class, or it might be that either CPU could excecute code held in the cache of the other chip
    i really dont think that there would be set rules for how java deals with such low level optimisation

  • Calling static synchronized method in the constructor

    Is it ok to do so ?
    (calling a static synchronized method from the constructor of the same class)
    Please advise vis-a-vis pros and cons.
    regards,
    s.giri

    I would take a different take here. Sure you can do it but there are some ramifications from a best practices perspective. f you think of a class as a proper object, then making a method static or not is simple. the static variables and methods belong to the class while the non-static variables and methods belong to the instance.
    a method should be bound to the class (made static) if the method operates on the class's static variables (modifies the class's state). an instance object should not directly modify the state of the class.
    a method should be bound to the instance (made non-static) if it operates on the instance's (non-static) variables.
    you should not modify the state of the class object (the static variables) within the instance (non-static) method - rather, relegate that to the class's methods.
    although it is permitted, i do not access the static methods through an instance object. i only access static methods through the class object for clarity.
    and since the instance variables are not part of the class object itself, the language cannot and does not allow access to non-static variables and methods through the class object's methods.

  • Projectname.exe' does not contain a static 'Main' method suitable for an entry point .

    Hi,
    I'm developing a blog reader for windows 8 store app. It was perfectly worked before. But because of some miss behave my coding i get below error. No other errors there.
    Error    1    Program 'c:\Users\.........\Desktop\Blog_Reader\Blog_Reader\obj\Release\intermediatexaml\Blog_Reader.exe' does not contain a static 'Main' method suitable for an entry point    C:\Users\..........\Desktop\Blog_Reader\Blog_Reader\CSC  
     Blog_Reader
    Please help me to figure this.
    Thank You!

    Go to your App.Xaml and R-Click Go to Properties
    Check whether the Build Action is ApplicationDefinition
    If not change it to ApplicationDefinition. Clean the code (solution ) and Deploy..
    Chears....

Maybe you are looking for