Local static variable not unique between dylib, Xcode 4.4.1 bug?

I am wondering if this is a Xcode bug or it is the way the c++ standart is.
I would expect to  see 1 in the console but i see 0.
Anybody know why? Here is the code
In one dylib I have
// Header file
class Foo {
   int i_ = 0;
   Foo(const Foo&) = delete;
   Foo& operator= (Foo) = delete;
   Foo()
public:
   void inc()
      ++i_;
   int geti()
      return i_;
   static Foo& get()
      static Foo instance_;
      return instance_;
   Foo( Foo&&) = default;
   Foo& operator= (Foo&&) = default;
int initialize()
   Foo::get().inc();
   return 10;
class Bar
   static int b_;
// cpp file
#include "ClassLocalStatic.h"
int Bar::b_ = initialize();
and in my application project i have
// main.cpp
#include <iostream>
#include "ClassLocalstatic.h"
int main(int argc, const char * argv[])
   std::cout << Foo::get().geti();
   return 0;
Thanks

thanks for your answer, You are right there is 2 foo singleton at different memory addresses.
I didn't think about when the dylib was loaded. I can't even tell when it is loaded. But I know if i but breaks point I break in the initialize function before breaking in main, but that might be because of this actual setup. So when does a dylib will be loaded? At the first call a program sees that need the dylib?
Here I'explain why it is done this way. My Singleton is a UnitTestRegistry, the Bar class is a UnitTest class and the static variable b_ is a class containing metadata info on the unit test.
I have a macro to define the unit test it is called Make_UnitTest()
So in a cpp I do
Make_UnitTest(MyTest)
     // Test Stuff
The macro will get expanded to
class MyTest_UnitTest: public UnitTestBase
     static UniTestMetaData b_;
     virtual void executeTest();
int MyTest_UnitTest::b_ = initializeAndRegisterUnitTest("MyTest_UnitTest", factoryFunction);
MyTest_UnitTest::executeTest()
// Test Stuff
And in the function initializeAndRegisterUnitTest I call the getInstance of the unit test  registry. This way my unit test are registred at loading time of the program/dll. If you know a better way to automatically register (i know it cuold be manual but i find it too cumbersome), but it wont fix the problem which is that I have two intance of my singleton because the function is inline in a header.
Well this behavior is surprising to me, I didn't know it would do this. But hey it is good to learn right!
Just to make it clear there is no real global!! The singleton is like a global but it is not completly one and the b_ is certainly not global it is a class static memeber...

Similar Messages

  • Session variable not passing between pages

    Hi, I've got a form that calculates checkbox values and puts them in a total field called txtTotal. When the user clicks send, I need to pass the total to a payment page.  The form page has PHP
    session_start();
    $_SESSION['sessTotal'] = $_POST['txtTotal'];
    and the payment page has
    session_start(); at the top of the page and <?php echo $_SESSION['sessTotal']; ?> where I want the total to display. The total does not carry over to the payment page and I can't work out why.
    Here is all the PHP from the form page as I'm pretty new to PHP and not sure if there's a conflict (should session_start appear more than once?)  Thanks guys
    <?php require_once('Connections/df.php'); ?>
    <?php
    //initialize the session
    if (!isset($_SESSION)) {
    session_start();
    $_SESSION['sessTotal'] = $_POST['txtTotal'];
    // ** Logout the current user. **
    $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
    if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
      $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
      //to fully log out a visitor we need to clear the session varialbles
      $_SESSION['MM_Username'] = NULL;
      $_SESSION['MM_UserGroup'] = NULL;
      $_SESSION['PrevUrl'] = NULL;
      unset($_SESSION['MM_Username']);
      unset($_SESSION['MM_UserGroup']);
      unset($_SESSION['PrevUrl']);
      $logoutGoTo = "index.php";
      if ($logoutGoTo) {
        header("Location: $logoutGoTo");
        exit;
    ?>
    <?php
    if (!isset($_SESSION)) {
      session_start();
    $MM_authorizedUsers = "";
    $MM_donotCheckaccess = "true";
    // *** Restrict Access To Page: Grant or deny access to this page
    function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
      // For security, start by assuming the visitor is NOT authorized.
      $isValid = False;
      // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
      // Therefore, we know that a user is NOT logged in if that Session variable is blank.
      if (!empty($UserName)) {
        // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
        // Parse the strings into arrays.
        $arrUsers = Explode(",", $strUsers);
        $arrGroups = Explode(",", $strGroups);
        if (in_array($UserName, $arrUsers)) {
          $isValid = true;
        // Or, you may restrict access to only certain users based on their username.
        if (in_array($UserGroup, $arrGroups)) {
          $isValid = true;
        if (($strUsers == "") && true) {
          $isValid = true;
      return $isValid;
    $MM_restrictGoTo = "index.php";
    if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {  
      $MM_qsChar = "?";
      $MM_referrer = $_SERVER['PHP_SELF'];
      if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
      if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
      $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
      $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
      header("Location: ". $MM_restrictGoTo);
      exit;
    ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
      if (PHP_VERSION < 6) {
        $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
      $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;   
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
      return $theValue;
    $colname_userDets = "-1";
    if (isset($_SESSION['MM_Username'])) {
      $colname_userDets = $_SESSION['MM_Username'];
    mysql_select_db($database_df, $df);
    $query_userDets = sprintf("SELECT usersId, userName, password, name FROM users WHERE userName = %s", GetSQLValueString($colname_userDets, "text"));
    $userDets = mysql_query($query_userDets, $df) or die(mysql_error());
    $row_userDets = mysql_fetch_assoc($userDets);
    $totalRows_userDets = mysql_num_rows($userDets);
    ?>

    OK I got it.  I needed 
    session_start();
    $_SESSION['sessTotal'] = $_POST['txtTotal'];
    on the payments page as well, not just session_start();

  • Static variable not static

    Hello
    I've got a little problem.
    I'm writing a Java program and I'm using five variables, all of them static Strings.
    However, at runtime, only four of them are seen as static, the other one is non-static.
    Can someone please explain why?
    Thank you
    later edit
    Actually this is an open-source project and I'm trying to modify a class. Is it somehow possible that they ( as in the authors of the code ) 'locked' the classes so that nobody else could modify them ? Every time I'm trying to add a method or a variable, I get a java.lang.NoSuchFieldError or java.lang.NoSuchMethodError. If this is possible, how is this done?
    Edited by: Nenea_Zap on May 22, 2010 11:02 AM

    OK, I tried it using the all-platforms JMF zip.
    I compiled successfully given the code you pointed to, unmodified.
    Then I added this to the class you mentioned:
    public int phony_number = 15;and was still able to compile successfully.
    The only issue in both cases was that the compiler complained about raw types (non-use of generics).
    I'd suggest creating a new project area, download the code clean, then confirm that you can compile it.
    Then clean the code out -- delete all class files and any jar files that are created as part of building -- make your modification, and compile again.
    If there's a problem post the compiler errors.
    My hunch is that you were compiling, with old version of class files in the classpath, confusing the compiler.

  • Static variables and JAR files problem

    Hello All,
    I am trying to get two applets to communicate.
    Both are held in the same JAR file loaded from the same location. The JAR file also contains a class with some static variables which are used to comunicate between the two applets.
    The applets are on separate frames in the browser and the system works fine when I don't use a JAR file but when I put the class files into a JAR file, each applet has it's own static variables (not very static).
    Can anyone tell me why static variables stop working when the code is loaded from a JAR file.
    Thanks in advance,
    Alastair.

    Ok,
    I've just tried the below setup and I get the following security exception:
    java.security.AccessControlException: access denied (java.util.PropertyPermission java.home read)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
    at java.lang.System.getProperty(Unknown Source)
    at sun.plugin.security.PluginClassLoader.getPermissions(Unknown Source)
    at java.security.SecureClassLoader.getProtectionDomain(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at appSend.init(appSend.java:62)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    I now have one JAR file which contains the two classes.
    appSend.class & appReceive.class
    and a separate details.class file
    The two HTML files are in separate folders but the JAR file is still the same for both.
    Classes\ -> contains the JAR file (myCode.JAR) and details.class
    Sender\ -> contains the HTML file appSender.html (see below for
    Applet tag)
    Receiver\ -> contains the HTML file appReceiver.html (see below for
    Applet tag)
    appSender.html
    <HTML>
    <HEAD>
    </HEAD>
    <BODY BGCOLOR="000000">
    <CENTER>
    <APPLET
    name = "appSender"
    code = "appSend.class"
    archive = "myCode.JAR"
    codebase = "../Classes"
    width = "500"
    height = "300"
    >
    </APPLET>
    </CENTER>
    </BODY>
    </HTML>
    appReceiver.html
    <HTML>
    <HEAD>
    </HEAD>
    <BODY BGCOLOR="000000">
    <CENTER>
    <APPLET
    name = "appReceiver"
    code = "appReceive.class"
    archive = "myCode.JAR"
    codebase = "../Classes"
    width = "500"
    height = "300"
    >
    </APPLET>
    </CENTER>
    </BODY>
    </HTML>
    Is this how it should be? or have I made a mistake with the tags?
    Can the ClassLoaders in either applet see the details.class file through the codebase tag?
    I'm guessing from the security exception that the ClassLoader for each applet can only load classes from within the JAR file? and can't just use the codebase tag, which is not very helpful!
    Thanks for your help so far.
    Regards,
    Alastair.

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • Is there any concept in LabVIEW that is similar to static local scope variables in C?

    I'd like to retain the value between calls to a subVI, as can be done using a static function scoped variable in C. The textbook example of how this is used would be a variable in the function that is a state machine, and knows what state it was in last time it was executed. A simpler example would be just keeping count of how many times the function has been called.
    I suppose I could use a global or I could pass values in and out of the subVI, but I'd like to keep the variable known only in the scope of the subVI if at all possible. For example, the outside world has no business knowing (or god forbid) changing what the state information of this function is.

    Bmarsh wrote:
    > I'd like to retain the value between calls to a subVI, as can be done
    > using a static function scoped variable in C. The textbook example of
    > how this is used would be a variable in the function that is a state
    > machine, and knows what state it was in last time it was executed. A
    > simpler example would be just keeping count of how many times the
    > function has been called.
    >
    > I suppose I could use a global or I could pass values in and out of
    > the subVI, but I'd like to keep the variable known only in the scope
    > of the subVI if at all possible. For example, the outside world has
    > no business knowing (or god forbid) changing what the state
    > information of this function is.
    There is no need to do something "conceptual" or spec
    ific to have this
    static variable. You already have this in any control or indicator in
    your sub-vi while it is in memory. Control/indicator value will remain
    in sub-vi data space between calls. Don't forget about make your sub-vi
    non-reentrant or keep track of sub-vi data space copies.
    If you want to read/write this value from another vi, consider it global
    or I'd prefer to suggest using functional global(uninitialized shift
    register in 1 iteration while loop). Think of it as about 1 value data
    repository.
    LabVIEW CIN reference manual is a good place to look at, as well as
    LabVIEW course kits, describing LabVIEW memory issues in details.
    To simplify: create empty sub-vi with control and indicator connected to
    each other and call it wiring indicator in caller vi. Keep sub-vi front
    panel open and change control in sub-vi manually. You see what happens.
    Sergey Krasnishov
    Automated Control Systems
    National Instruments Alliance Member
    Mos
    cow, Russia
    [email protected]
    http://acs.levsha.ru

  • Static variable could not seem as attribute in JMX

    Hi,
    I defined a Global class and I have a static variable. I could not see them as attribute in jConsole. BTW, the methods could seem in jconsole. And, I used the class includes static variables as a Global class.
    How can i see the static variable in jconsole?

    Global class is a final Class it is not be instantiated.
    Static variables should be accessible because I want to monitor something ( for example file processing time or file sending time .. ). I set the variable as average time of file processing and I would like to monitor in jmx.
    In application-context xml in spring environment I represent the bean as mbean as below :
         <bean id="exporter3" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
         <property name="beans">
              <map><entry key="bean:name=Global" value-ref="Global"/></map>
         </property>
         </bean>

  • Error on compile - non-static variable can not be referencedfrom static con

    Error on compile happening with addButton?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    public class Log implements ActionListener {
    JButton addButton;
    public static void addComponentsToPane(Container pane) {
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
         c.gridy = 3;
    c.gridx = 0;
         JLabel callsignLabel= new JLabel("Callsign");
    pane.add(callsignLabel, c);
         c.gridy = 3;
    c.gridx = 1;
         JLabel nameLabel= new JLabel("Name");
    pane.add(nameLabel, c);
         c.gridy = 3;
    c.gridx = 2;
         JLabel timeLabel= new JLabel("Time");
    pane.add(timeLabel, c);
         c.gridy = 3;
    c.gridx = 3;
         JLabel dateLabel= new JLabel("Date");
    pane.add(dateLabel, c);
         c.gridy = 3;
    c.gridx = 4;
         JLabel frequencyLabel= new JLabel("Freq ");
    pane.add(frequencyLabel, c);
         c.gridy = 3;
    c.gridx = 5;
         JLabel locationLabel = new JLabel("Country/State");
    pane.add(locationLabel, c);
    c.gridy = 5;
    c.gridx = 0;
         addButton = new JButton("Add");
    pane.add(addButton, c);
         addButton.addActionListener(this);

    Thank you for the reply
    I am new to Java
    What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
    If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again.

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • Static Variable in webapplication

    Are the values of static variables preserved when two different users try and access them? i.e.
    If one web application user sitting in Chicago sets a static variable to 'true' from 'false'. Will the other user sitting in Omaha see it as 'true' or 'false' in his session?

    Alright, I did this test.
    1) On my local tomcat I created a mini webapp where I
    declared a static which populates from a form field.
    static String displayname = "";
    displayname = request.getParameter("username");
    and then displayed it on the html page.
    2) I opened IE sessions of my application and in one
    I gave the user name 'Tom' and other 'Janet' and hit
    continue. (Tom before Janet)
    3) The page that had 'Tom' displayed tom and other
    one Janet. Then I refreshed the display page for the
    tom instance and it still showed 'Tom'.
    Conclusion: It appears that the statics are indeed
    loyal to the class loader and not the JVM. Hence, for
    multiple users each instance should have its own
    static.
    Please let me know if you disagree or see my test to
    be wrong.
    Thanks
    Message was edited by:
    Birthdayhitting the refesh button on your IE page doesn't show you what the value of the static variable in your web app is. You're headding for trouble.
    EDIT: Ok well it depends on you implementation how the refresh will work, but if you have a static fields in a class on your web server I promise you it's not in any way associated with any session.

  • "non-static variable cannot be referenced from a static contex"

    Hi, i'm writing a booking program at school and i'm getting 27 "non-static variable cannot be referenced from a static contex" errors. I can't find anything wrong with the code so I'm just asking you guys to look it through..
    public class bokningsmeny
    Bokning[] bokningslista = new Bokning[1000];
    String fornamn;
    String efternamn;
    String civilstand;
    String adress;
    String personnr;
    String telefonnr;
    int regnr;
    double inkomst;
    public static void main(String[] args)
    for(;;)
    System.out.println("\nMeny");
    System.out.println("________\n");
    System.out.println("1. Mata in nya personer.");
    System.out.println("2. S&ouml;k personen via personnummer och skriv personens andra uppgifter.");
    System.out.println("3. S&ouml;k personen via efternamn och skriv personens andra uppgifter.");
    System.out.println("4. S&ouml;k personen via personnummer och &auml;ndra adress.");
    System.out.println("5. S&ouml;k personen via personnummer och &auml;ndra telefonnummer.");
    System.out.println("6. S&ouml;k personen via personnummer och &auml;ndra civilst&aring;nd.");
    System.out.println("7. S&ouml;k personen vis personnummer och &auml;ndra inkomst");
    System.out.println("8. Skriv ut alla personer med givet namn.");
    System.out.println("9. Skriv ut alla personer med givet efternamn");
    System.out.println("10. Skriv ut alla personer med given adress");
    System.out.println("11. Skriv ut hela listan");
    System.out.println("12. Avsluta\n");
    int menyval = Keyboard.readInt();
    System.out.println("\n");
    switch(menyval)
    case 1:
    System.out.println("Mata in nya personer.\n______________________\n");
    boolean BOOuppgifter = false;
    for(int i = 0; i <= 1000; i++)
    if(bokningslista +== null)+
    +{+
    +SkrivInUppgifter();+
    +System.out.println("\nSt&auml;mmer informationen? (Y/N)");+
    +boolean BOOcase1yesorno = IsInputCorrect();+
    +if(BOOcase1yesorno == true)+
    +{+
    +System.out.println("\nBokningen lyckades!\n");+
    +bokningslista += new Bokning(fornamn, efternamn, civilstand, adress, personnr, telefonnr, regnr, inkomst);
    ++++else if(BOOcase1yesorno == false
    ++++System.out.println("\nBokningen avbruten.\n")
    ++++break
    ++++++break
    ++++case 2
    ++++System.out.println("Sok person med personnummer och &auml;ndra uppgifter.")
    ++System.out.println("___________________________________________________________\n")
    ++System.out.print("Skriv in sokord: ")
    ++String query = Keyboard.readString()
    ++query = query.toUpperCase()
    ++String personnummersok
    ++boolean contains
    ++int antal = 0
    ++boolean BOOcase2result = false
    ++System.out.println("Resultat: \n_________\n")
    ++for(int i = 0; i < 1000; i++
    ++++if(bokningslista +!<b<br />+<em<b<br />+++personnummersok = (bokningslista+.hamtaPersonnum()).t
    ++++contains = personnummersok.con
    ++++if(cont
    +<<br />++++BOOcase2r
    ++++ant
    ++++fornamn = bokningslist
    +++++efternamn = boknin
    ++++++personnr
    +++++++System.out.println(antal + ". " + fornam
    ++++<e<br />+++++++System.out.pri<br<br />+++++<em<br />+++++++System.out.println("\nVilket sokresultat vill du v&bdquo
    ++++<<br />+++++++if(case2ch
    +++++++System.ou
    +++<e<<br />+++<em<br />++++
    ++<em<br />+++++++System.out.p
    +++++<e<br />+++<<br<br /<br />+++++++System.out.printl
    +++<em<br />+++++<em<br />++
    <e<br />++++++++Sy
    +++++
    ++++++<e<br /><em<br />++++++++<<br />+++++<e<br />+++
    +++<<br />+++++++++else if(case11exit != 'y' &<br<br />+<<br />++++
    ++++
    +++++
    ++++<e<br />+++++++
    ++++<em<br />+++++
    +++<em<br />+++++<em<br />++++<<br />++++++
    ++++<e<br />+++++++<e<br />++<em<br />++++<e<br />+++<<br />+++++++++System.out.println("\n\nNamn: " + fornamn + "
    ++++++++++ "\nHemadress: " + adr
    ++++++++++ telefon
    +<<br />+++++++++Syste
    ++++<em<br />+++++++++if(correct
    <em<br />++<em<br />++<<br />++++<e<br /><<<br /><e<br />+++++++++I have another file with the Bokning.java class in it but I know for sure that its error free. Notice that I'm not nearly done with the program, theres like 10 more 'cases' to be created but I dont w
    ++<em</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Your code goes "+" crazy there, but here is your problem:
    public class B extends A {
        public void method() {}
        public static void main(String[] args) {
            //method(); //non-static method method() cannot be referenced from a static context
            B b = new B();
            b.method();
    }You need to be clear about the difference between static methods and non-static (instance) methods. Instance methods are applied to objects.

  • Can the output of a Generate Occurrence be passed in Local/Global Variable?

    Can the output of a Generate Occurrence function, which is a refnum, be passed in Local/Global Variable so that it does not need to be wired to all parties directly?
    Can more than one party be waiting on the same Occurrence and will all waiting function be released together?

    dbaechtel wrote:
    Answer was not given:
    Can the output of a Generate Occurrence function, which is a refnum, be passed in Local/Global Variable so that it does not need to be wired to all parties directly? Is this possible?
    I am not worried about whether it is bad form or not, as yet. That is for me to decide on a case by case basis.
    Yikes! That is not a very good way to learn.
    Anyways, to avoid any more bold emphasis on words, I will answer your question. Locals can only be linked to controls/indicators not individual wires. If you want to get the effect of a local/global variable with a wire value, search the forum for action engines or functional globals. Those will work for passing a wire value between threads.
    That said, what are you trying to use occurences for? There may be (and probably is) a more accepted way to implement what you are trying to do instead of using local variables
    CLA, LabVIEW Versions 2010-2013

  • Static variable

    Why is that Java does not allow the declaration of a variable in a method, which may be static method or a non-static method to be a static variable? Is there any specific reason for that ....????
    The other thing is that if i declare a constructor as a private member in the class so as to restrict the number of objects which can be created. But if i do write is the main in the same class then i can straigthaway can create the objects as if the constructor is public.i.e. i can use is the new operator.......if the same if i have a containment kind of instantion then it says that it cannot access the private member in which i write is a factory method. Why so ? why is the main able to access the private members of the class.....by this we say the idea of encapsulation is being voilated.......
    Regds,
    Jay

    Why is that Java does not allow the declaration of a
    variable in a method, which may be static method ora
    non-static method to be a static variable? Is there
    any specific reason for that ....????
    methods are either static or non-static therefore
    method variables of a static method are intrinsically
    static just as members of a private method (putting
    aside the scope of the method for a moment) are
    intrinsically private. Why on earth would you want to
    make a method variable specifically static?
    This makes no sense.members of a private method are not public or private or anything. Well this could be explained better in terms of closure. Closures relate to the life-time of local variables (and parameters). In Java, any time a method is called, a new set of the method's local variables (and parameters) are allocated upon the stack. For Java, an environment is typically implemented as a stack allocated activation record. When a method returns, the environment associated with the current activation is discarded. This is why you can have multiple activation of a method (for example a recursive method) and each activation has its own private set of local variables.
    >
    >
    The other thing is that if i declare a constructoras
    a private member in the class so as to restrict the
    number of objects which can be created. But if i do
    write is the main in the same class then i can
    straigthaway can create the objects as if the
    constructor is public.i.e. i can use is the new
    operatorI presume you mean main() method signature which must
    be public and static. Well ...Main method signature is always public and static except if you are talking about the bug until java 1.4
    1. We'd all be a bit stuffed if it wasn't
    2. The private class constructor is only visible from
    the class where the access modifier is declared, this
    isn't to say that the constructor is public at all as
    it is inaccessible from outside other than the system
    call to java, jar, jajaw or whateverThe accessor private doesnot limit the access to the members of the class in question. And the reason you would like to implement something like a singleton wouldnot be from within the same class definition but from other classes.
    >
    >
    .......if the same if i have a containment
    kind of instantion then it says that it cannotaccess
    the private member in which i write is a factory
    method. Why so ?I assume because you made it private, that is what you
    asked for, the method is hidden and not accessible
    outside the class. This is encapsulation.
    why is the main able to access the
    private members of the class.....by this we say the
    idea of encapsulation is being voilated.......
    No, not at all as it is only accessible from main
    which merely launches the program.
    I think you need to answer for yourself a question
    asked in this forum just a few days ago ===> why is
    main() static and public and void?And I would also suggest going through the factory patterns once again.

  • Problem with BP. Assignment: Business partner person to user not unique

    I have a problem with a user. They have no BP assigned in PPOSA_BBP. We have found a BP in transaction BP.
    When we try the BBP_BP_OM_INTEGRATE the message BBP_UM_UI048 appear" Assignment: Business partner person to user not unique" .
    Any idea about how solve this??
    Best regards
    Jorge

    Hi
    Which SAP version are you using ?
    The user needs to be attached to the Org Plan. (PPOMA_BBP)
    Have you maintained the Contact person for this USer in the Org Plan. (PPOMA_BBP) ?
    Please check the consitency of this BP as well.
    Have you read the documenattion of the Transaction -> BBP_BP_OM_INTEGRATE ?
    If no, here it is..
    Transaction -> BBP_BP_OM_INTEGRATE
    Short text
    Object Synchronization and Repair
    Purpose
    This report enables you to run a consistency check for the integration of HR Master Data and Business Partner data. If not all data exists for the business partner, you can first synchronize data. When synchronization is run for organizational units, the basic data (name, description) and the address data is included; when synchronization is run for central persons, bank information is included in addition to the basic data and address data.
    Prerequisites
    To be able to run this report, integration between Organizational Management and SAP Business Partner must be active.
    Features
    This section contains information about the functions you can use to select and output data.
    Selection
    The following options enable you to restrict the selection of objects:
    Central Person
    In addition to selecting central persons created during integration between HR Master Data and Business Partner data, you can also select central persons who have been created locally. However, central persons created locally are not checked for consistency.
    Employee (object type P)
    This selection option is only available in HR systems. The corresponding central person is displayed together with the person. Both objects are kept consistent in the Basic Data, Address, and Bank Data columns.
    Positions
    Business Partners (Employee role)
    Users
    Organizational Unit(s)
    You can specify specific organizational units for the selection.
    Business Partner (Organizational Unit role)
    Note:
    The selection objects Position, Business Partner (Employee role), User, and Business Partner (Organizational Unit role) are only available if an implementation of BAdI HRALX_HRALXSYNC_BADI exists.
    Branch as of Organizational Unit
    This option enables you to select all objects in the structure for one or more organizational units. You can also restrict selection according to one of the following object types:
    Central Persons Only
    Employees Only
    Positions Only
    Business Partners Only (Employee role)
    Users Only
    Organizational Units Only
    Business Partners Only (Organizational Unit role)
    Include All Object Types
    Changes Since
    All organizational units and central persons for which changes have been made since the last time all objects were synchronized are read. When all objects have been synchronized successfully, a new change date is set.
    Note:
    If a selection has been made but the relevant input field remains blank, all objects of a particular object type are read from the database. This condition can lead to a long runtime, therefore, SAP recommends you also enter a restriction.
    Output
    The organizational units and central persons that have been found are displayed in a list that includes status data.
    To facilitate navigation, a hierarchical tree structure is displayed on the left-hand side of the object list. The branches are sorted according to the type of action that is to be executed.
    If an implementation of BAdI HRALX_HRALXSYNC_BADI exists, checks from this BAdI are executed in the External Checks branch.
    If you double-click on the folder icon in the navigation tree, all objects are displayed in the list.
    Note:
    Meaning of status display for data in the Basic Data, Address, and Bank Data columns:
    Icon Message Text Meaning
    Green traffic light Business partner does not need to be synchronized with HR object data All business partner data is consistent with HR object data.
    Yellow traffic light Business partner does need to be synchronized with HR object data Business partner exists. The business partner data is not consistent with the HR object data.
    Red traffic light Object data is new and must first be created for the business partner The business partner does not yet exist or the the business partner data is incomplete.
    No traffic light Object type does not include this type of data Check type is not relevant for this object.
    Activities
    To integrate business partners or to repair selected objects, you must select the relevant lines in the object list and choose Execute. Any errors that occur are displayed after synchronization.
    Hope this will help.
    Please reward suitable points, incase it suits your requirements.
    Regards
    - Atul

  • I want to use static variable instead of using variable in servlet context

    Hi all,
    In my web application i have to generate a unique Id.
    For this, At the application startup time i am connecting to the database and getting the Id and placing it in the servlet context.
    Every time i am incrementing this id to generate a unique id.
    But, now i want to place this id in a static variable which is available to all the classes.
    why i want to do this is to reduce burden on servlet context.
    my questing is, is this a best practice ? If not please give me your valuable suggestion.
    thanks
    tiru

    There isn't a problem with this as long as you want to share the value of that variable with all requests. If this is read-only except when it is first set then you're fine. The only real issue will be how to initialize and/or reinitialize the variable. When the servlet is started, how will you get the value for the variable? If the servlet is shutdown and restarted (a possibility in any application server) how will you re-read the variable? You need to answer these questions to decide the best route. It may be as simple as a static initializer or it may be more complex like a synchronized method that is called to see if the variable is set.

Maybe you are looking for