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.

Similar Messages

  • Why are protected fields not-accessible from sub-classed inner class?

    I ran across a situation at work where we have to sub-class an inner class from a third-party package. So, it looks something like this...
    package SomePackage;
    public class Outer {
       protected int x;
       public class Inner {
    package OtherPackage;
    public class NewOuter extends Outer {
       public class NewInner extends Outer.Inner {
    }Now the NewInner class needs to access protected variables in the Outer class, just like the Inner class does. But because NewOut/NewInner are in a different package I get the following error message.
    Variable x in class SomePackage.Outer not accessible from inner class NewOuter. NewInner.You can still access those protected variables from the NewOuter class though. So, I can write accessor methods in NewOuter for NewInner to use, but I am wondering why this is. I know that if NewOuter/NewInner are in the same package as Outer/Inner then everything works fine, but does not when they are in different packages.
    I have to use JDK1.1.8 for the project so I don't know if there would be a difference in JDK1.2+, but I would think that nothing has changed. Anyway, if you know why Java disallows access as I have detailed please let me know.

    Although I don't have the 1.1.8 JDK installed on my system, I was able to compile the following code with the 1.3.1_01 JDK and run it within a Java 1.1.4 environment (the JVM in the MSIE 5.5 browser). As long as you don't access any of the APIs that were introduced with 1.2+ or later, the classes generated by the JDK 1.2+ javac are compatible with the 1.1.4+ JVM.
    //// D:\testing\SomePackage\Outer.java ////package SomePackage ;
    public class Outer {
        protected int x ;
        public Outer(int xx) {
            x = xx ;
        public class Inner {
    }//// D:\testing\OtherPackage\NewOuter.java ////package OtherPackage;
    import SomePackage.* ;
    public class NewOuter extends Outer {
        public NewOuter(int xx) {
            super(xx) ;
        public class NewInner extends Outer.Inner {
            public int getIt() {
                return x ;
    }//// D:\testings\Test.java ////import OtherPackage.* ;
    import java.awt.* ;
    import java.applet.* ;
    public class Test extends Applet {
        public void init () {
            initComponents ();
        private void initComponents() {
            add(new Label("x = ")) ;
            int myx = new NewOuter(3288).new NewInner().getIt() ;
            TextField xfld = new TextField() ;
            xfld.setEditable(false) ;
            xfld.setText(Integer.toString(myx)) ;
            add(xfld) ;
    }//// d:\testing\build.cmd ////set classpath=.;D:\testing
    cd \testing\SomePackage
    javac Outer.java
    cd ..\OtherPackage
    javac NewOuter.java
    cd ..
    javac Test.java//// d:\testing\Test.html ////<HTML><HEAD></HEAD><BODY>
    <APPLET CODE="Test.class" CODEBASE="." WIDTH=200 HEIGHT=100></APPLET>
    </BODY></HTML>

  • Why a static class can implements a non-static interface?

    public class Test {
         interface II {
              public void foo();
         static class Impl implements II {
              public void foo() {
                   System.out.println("foo");
    }Why a static class can implements a non-static interface?
    In my mind, static members cann't "use" non-static members.

    Why a static class can implements a
    non-static interface?There's no such thing as a non-static member interface. They are always static even if you don't declare them as such.
    An interface defines, well, a public interface to be implemented. It doesn't matter whether it is implemented by a static nested class or by an inner class (or by any class at all). It wouldn't make sense to enforce that it should be one or the other, since the difference between a static and non-static class is surely an irrelevant detail to the client code of the interface.
    In my mind, static members cann't "use" non-static
    members.
    http://java.sun.com/docs/books/jls/third_edition/html/classes.html#246026
    Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier.

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

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

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

  • Private static class

    hi, what is the point of having a private static class, as you cannot acces it outside the scope of a class?

    hi, what is the point of having a private static
    class, as you cannot acces it outside the scope of a
    class?There are lots and lots of uses. The private implementation can actually be exported outside of the outer class if implements a public interface.

  • 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();
    }

  • Setting private fields from Parent class.

    Hi all, I have what seems to be a weird situation to me.
    Basically I have two classes:
    import java.lang.reflect.Field;
    public class Parent {
         protected void ensureDefaults() {
              Field[] declaredFields = getClass().getDeclaredFields();
              for (Field field : declaredFields) {
                   Object fieldValue = getDefaultValueForType(field.getType());
                   try {
                        System.out.println("defaulting field - name: " + field.getName() + " | this: " + this);
                        field.set(this, fieldValue);
                   } catch (Exception e) {
                        e.printStackTrace();
         private Object getDefaultValueForType(Class<?> type) {
              Object defaultValue = null;
              if (type.isAssignableFrom(String.class)) {
                   defaultValue = "default";
              } else if (type.isAssignableFrom(int.class)) {
                   defaultValue = -100;
              return defaultValue;
    public class Child extends Parent {
         private String name;
         private int age;
         public Child() {
              ensureDefaults();
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public int getAge() {
              return age;
         public void setAge(int age) {
              this.age = age;
    // Test Case
    import junit.framework.TestCase;
    public class ChildTest extends TestCase {
         public void testEnsureDefaults() {
              Child child = new Child();
              assertEquals("default", child.getName());
              assertEquals(-100, child.getAge());
    }The odd thing to me is that the output looks like:
    defaulting field - name: name | this: Child@7431b9
    java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
    ... more exception ...
    defaulting field - name: age | this: Child@7431b9
    java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
    ... more exception ...
    As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private. However, if you look it's saying that "this" is a Child, so shouldn't those fields be accessible? Shouldn't ensureDefaults be executed as if it was being called by the Child instance?
    Obviously, I can try to use the accessor methods, but that means creating strings for method names, and then looking for the methods. I'd like to avoid this and it seems to me this should work, no?
    Another odd thing is that if I change the fields in Child to protected, it works fine.
    Also, I'm not sure if this is important (I don't know enough about security managers to know if they're different platform to platform, version to version), I'm on a Mac OSX 10.4.11 and:
    java version "1.5.0_13"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
    Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
    Any help with this would be greatly appreciated.
    Thanks,
    Eric

    jschell wrote:
    As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private.Myself I don't like it because it suggests a design problem which is associated with understanding that although a child is a parent that doesn't mean that a parent is a child.
    I understand that, but I don't see how this actually breaks that. The Child is executing a method that is passed down to it from it's Parent, but it's executing it as itself - by that I mean it's not looking at anything that it can't already look at, or at least I thought it was.
    Shouldn't ensureDefaults be executed as if it was being called by the Child instance?No.Ok, I thought it was. Can you please explain this a bit more, I want to understand it.
    >
    Another odd thing is that if I change the fields in Child to protected, it works fine.If you messed with reflection some more you could get to to work even with private. How exactly? I really don't want to bypass any security measures (by settings accessible or using a different security manager, or anything like that). As I mentioned in my last post, what I want to do really is nothing more than a nice way to have a generic toString or hashCode method, if it's not possible to do it nicely - within java's default constraints, I'd rather not.
    >
    However in general the idiom would still be wrong.I'm moving more towards using beans anyway, so I plan on just calling accessor methods which corrects the "wrong idiom" right?
    Thanks for all the help,
    Eric

  • Accessing private field of Derived object in Base class

    Hi,
    I have this piece of code I wrote a while ago to test something. The issue is accessing a private field of Base class in Base but of a Derived object.
    Here is the code:
    class Base
         private int x;
         public int getX()
              return x;
         public int getX(Derived d)
              // return d.x;
              return ((Base) d).x;
    }The commented code does not work but casting d to Base does.
    Can someone please explain the reasoning for this.
    Forgot to mention that the compilation error is that x has private access in Base.
    Thank you.
    Edited by: 953012 on Apr 1, 2013 8:42 AM

    >
    As I understand the explanation says that you can access any private member within the code of the class that encloses the private member. So in this case x is the private member and the line of code (return d.x) is in Base which encloses the private member. Does it have to do with the fact that the Derived class does not in fact inherit the private members of Base?
    >
    It has to do with the entire quote from the spec
    >
    A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses
    >
    Your code is
    public int getX(Derived d)
              // return d.x;
              return ((Base) d).x;
         }The 'Derived' class is NOT 'the top level class that encloses the declaration of the member'. It does NOT inherit 'x' which is a private member of 'Base'. As far as the 'Derived' class is concerned 'x' does not exist.
    >
    If outside Base code I have Derived d = new Derived() and I call d.getX() then isn't that like calling d.x in myX()?
    >
    How is that the same? 'Base' owns 'x' and can do whatever it wants with it. 'Derived' has no knowledge of 'x' and CAN NOT access it.

  • How to get private fields from super class?

    Hi.
    I must get protected and private fields from a class. I know that sounds werid but I have a very good reason for doing so, ask if you want.
    I have tried the getDeclaredField(String) method, but it apparently doesn't return the fields declared by the super classes.
    What's the smartest solution to this?
    Thank you all.
    edit: note that the superclass hierarchy's length is 3 and that there are several classes at the bottom level.
    Edited by: bestam on Sep 24, 2009 2:05 PM

    bestam wrote:
    I do not claim I have invented a new programming language Sir, you must be mistaken. This is not turing complete.
    This is a language for describing Cards or a game's rules if you want.
    AspectJ isn't Turing complete but AspectJ is still a compiler.
    This is how I have been working :
    - I have implemented the core library in Java (what is a Player, what is an Effect, what is a Card, what is a BuildingCard, what is a Player's Turn and so on)
    - It also includes packages dedicated to service, able to retrieve and send data to the clients via sockets.
    - Then I have "hardcoded" a dozen of specific cards in Java, for testing and validating the core library. I have been doing so by extending the BuildinCard's class for example.
    - But my ultimate goal is not to code thoses 1.000+ cards of the game in Java. I chosed to design a little language so that I would end up writing cards faster. While I'm traversing the syntactical tree representing the card, I feed the card's fields one by one. Some of them are quite primitive, some other are more complex and have a recursive nature for instance.
    Providing detail for how you implemented it doesn't change anything about what I already said.
    Thus, this is not really a compiler as it doesn't transform a text in language A into a text in language B.
    You really need to understand more about what "compilers" and certainly compiler theory do before you decide what they can and cannot do.
    And your statement still does not change what I said.
    Is this wrose than the bean design pattern from JSP ? I'm not sure.
    Bean design? A "bean" has almost zero requirements.
    Aside of that, it's a bit harsh to be told "read the fucking manual" while I have written my first compiler some years ago.Not sure who that was directed. I suggested some reading material on compiler theory.
    If you think that your idea is ideal then knock yourself out. Since I doubt I will end up seeing it in anything that I must maintain it doesn't matter to me. But you did in fact ask what the best solution was.

  • Error LNK2028: unresolved token (0A00001F) "public: static class oracle....

    Hello,
    I am using MSVC C++ Express and Oracle XE. When I am building my C++ script I get the following errors:
    DbCheck.obj : error LNK2028: unresolved token (0A00001F) "public: static class oracle::occi::Environment * __clrcall oracle::occi::Environment::createEnvironment(enum oracle::occi::Environment::Mode,void *,void * (__clrcall*)(void *,unsigned int),void * (__clrcall*)(void *,void *,unsigned int),void (__clrcall*)(void *,void *))" (?createEnvironment@Environment@occi@oracle@@$$FSMPAV123@W4Mode@123@PAXP6MPAX1I@ZP6MPAX11I@ZP6MX11@Z@Z) referenced in function "int __clrcall main(cli::array<class System::String ^ >^)" (?main@@$$HYMHP$01AP$AAVString@System@@@Z)
    DbCheck.obj : error LNK2019: unresolved external symbol "public: static class oracle::occi::Environment * __clrcall oracle::occi::Environment::createEnvironment(enum oracle::occi::Environment::Mode,void *,void * (__clrcall*)(void *,unsigned int),void * (__clrcall*)(void *,void *,unsigned int),void (__clrcall*)(void *,void *))" (?createEnvironment@Environment@occi@oracle@@$$FSMPAV123@W4Mode@123@PAXP6MPAX1I@ZP6MPAX11I@ZP6MX11@Z@Z) referenced in function "int __clrcall main(cli::array<class System::String ^ >^)" (?main@@$$HYMHP$01AP$AAVString@System@@@Z)
    F:\Visual C++ Projects\DbCheck\Debug\DbCheck.exe : fatal error LNK1120: 2 unresolved externals
    I downloaded OCCI for Visual C++ 8 (Windows) Download (zip). but still get the error. I also linked oraocci10.lib and oraocci10d.lib but still nogo. I did it in the project property page under linker->input->additional dependencies. The configuration I choosed was:
    Configuration: Debug
    Platform: Win32
    Is there a way to determine what is missing or what is causing the error, does one of you know how to solve the problem?
    Thanks
    Rodger

    Could you try to create a CLR command line application and get that to run first ?
    This example here links and runs fine for me (it is a bit messy since I've been experimenting with my own mem leak problems, but it runs fine, you might want to change the select statement though)
    (The stdafx.h file only contains #pragma once, the TestRead class is there just to test mapping from std::string to System::String)
    #include "stdafx.h"
    #include <occi.h>
    using namespace System;
    using namespace std;
    using namespace oracle::occi;
    public ref class TestRead
    public:
         System::String^ GetStr(int index);
    internal:
         oracle::occi::ResultSet* m_resultSet;
    System::String^ TestRead::GetStr(int index)
         try
              return gcnew System::String(m_resultSet->getString(index).c_str());
         catch (const oracle::occi::SQLException& ex)
              throw gcnew System::Exception(gcnew System::String(ex.getMessage().c_str()));
         return "";
    int main(array<System::String ^> ^args)
    try
         oracle::occi::Environment *env = oracle::occi::Environment::createEnvironment((oracle::occi::Environment::Mode)(oracle::occi::Environment::OBJECT | oracle::occi::Environment::THREADED_MUTEXED));
    Connection *conn = env->createConnection("test","test","");
    try
    oracle::occi::Statement *stmt = conn->createStatement("Select site_addr From parcel");
    oracle::occi::ResultSet *rs = stmt->executeQuery();
         TestRead^ testread = gcnew TestRead();
         testread->m_resultSet = rs;
    //int MktId;
    string MktName;
    int rowno = 1;
    while (rs->next())
              System::String^ name = testread->GetStr(1);
    rowno++;
         // if (rowno > 100)
         //     break;
    stmt->closeResultSet(rs);
    conn->terminateStatement(stmt);
    catch (SQLException &ex)
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
    throw;//re-throw
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
    catch (SQLException &ex)
    Console::WriteLine(L"Hello World");
    return 0;
    }

  • 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 reference

    Below we have a class containing a static class variable and a static accessor method.
    The method is responsible for assigning the variable, which it does on demand.
    public class MyClass
        private static int INFO = -1;
        public static int getInfo()
            if(INFO < 0)
                try
                    INFO = ...;
                catch(Exception e)
            return INFO;
        }When using this class is it not safe to assume that the assignment of the variable will ever only occur once for the life of the system that uses this class? (afterall is it static within the class)
    I am experiencing the situation whereby EVERY time the method is called, the assignment of the variable is necessary. I can only assume that the static instance of this class in memory has been lost between each call and therefore the state/value of the variable has also been lost.
    It is worth noting that no object instances of this class are ever created. The class is accessed only through its static interface. It seems that since no local reference to objects of this class are held in memory then the entire class, along with its internal static state, is cleared from memory (garbage collected?).
    How is it possible to ensure that the state of static fields within such a class is preserved over time, without create instances of the class.
    John

    When using this class is it not safe to assume that
    the assignment of the variable will ever only occur
    once for the life of the system that uses this class?First of all, you haven't said what you assign it to, so we can't say. If you assign a value less than zero then it will be reassigned next time the method is called.
    Secondly, it depends on whether or not you're expecting it to be thread-safe? It isn't.
    If your code is not multi-threaded, then the section of code in your getInfo method that assigns the field should only execute once during a single run of an application.
    Thirdly, you explicitly assign it (to minus one) at class initialisation time, so stricty speaking, the variale will always be assigned at least once, and will be assigned at least once more if the getInfo method is ever called.
    I am experiencing the situation whereby EVERY time the
    method is called, the assignment of the variable is
    necessary. Can you offer any evidence to this? A small, complete, compilable and executable example that demonstrates the problem will help, and will probably get you an answer pretty quickly around here.
    I can only assume that the static instance
    of this class in memory has been lost between each
    call and therefore the state/value of the variable has
    also been lost.Then either there is a bug in your JVM, or at least two versions of the class have been loaded, and at least one of those was not loaded by the system classloader. Without further info, we aren't going to be able to help much more here.
    The class is accessed only
    through its static interface. It seems that since no
    local reference to objects of this class are held in
    memory then the entire class, along with its internal
    static state, is cleared from memory (garbage
    collected?).This is not allowed under the JLS if the class was loaded by the system classloader. If it was loaded by another classloader, then it is only allowed if it can be determined that the class will never again be used throughout the entire run of the application. Since you are referencing the class again, this should not be happening.
    How is it possible to ensure that the state of static
    fields within such a class is preserved over time,
    without create instances of the class.From what you have told us so far, it should be. You will probably have to provide some code for us to help you further.

  • Static class variable doesn't store ?

    Hi,
    I'm a beginner in java.
    I defined a static class variable (nodes) in th following code :
    public class MySOMapp extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         private static SOMTrainer trainer;
         private static SOMLattice lattice;
         private static SOMNode nodes;
         private static Hashtable nwordf; 
         public MySOMapp(String args[]) {
              SOMNode nodes = new SOMNode();          //.....But a method of this class, nodes comes null. methos definition :
    private void makesame() {I don't understand why the nodes is null in makesame method which is in the same class with nodes ?
    thanks,
    Yigit

A: static class variable doesn't store ?

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

  • How to get the private and public key?

    there is my code,i want to get the public key and the private key �Cbut i could not find the the approprite method to solve the problem.
    import java.security.Key;
    import javax.crypto.Cipher;
    import java.security.KeyPairGenerator;
    import java.security.KeyPair;
    import java.security.Security;
    public class PublicExample {
    public static void main(String[] args) throws Exception {
    if (args.length != 1) {
    System.err.println("Usage:java PublicExample <text>");
    System.exit(1);
    byte[] plainText = args[0].getBytes("UTF8");
    System.out.println("\nStart generating RSA key");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(512);
    KeyPair key = keyGen.generateKeyPair();
    System.out.println("Finish generating RSA key");
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    //System.out.println("\n" + cipher.getProvider().getInfo());
    System.out.println("\nStart encryption");
    cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
    byte[] cipherText = cipher.doFinal(plainText);
    System.out.println("Finish encryption:");
    System.out.println(new String(cipherText, "UTF8"));
    System.out.println("\nStart decryption");
    cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
    /*i want to get the private and public key in this method ,but i found the result was not
    the one i expected to get,how to solve the problem?
    thanks in advance!
    System.out.println("private key:" + key.getPrivate().toString());
    System.out.println("public key:" + key.getPublic().toString());
    byte[] newPlainText = cipher.doFinal(cipherText);
    System.out.println("Finish decryption:");
    System.out.println(new String(newPlainText, "UTF8"));
    thanks in advance!

    System.out.println("private key:" +
    " + key.getPrivate().toString());
    System.out.println("public key:" +
    + key.getPublic().toString());
    key.getPrivate() returns an instance of PrivateKey and key.getPublic() returns an instance of PublicKey. Since PublicKey and PrivateKey are interfaces then they will return one of the concrete implementations. Check out the Javadoc for PublicKey and PrivateKey.
    When you know which concreate implemenation you have then you can use the methods on that object (by appropriate casting) to find the information you want.

  • 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

  • Maybe you are looking for

    • OIM 9.1 Xellerate User Provision form

      Hi, I want to add a process task to Xellerate user form and form that is cretaed while configuring Generic connector. But it seems that those are disabled. Does it mean that no modification can be done on thses forms? Thanks

    • How do i get iDVD on my macbook pro?

      How do i get iDVD on my macbook pro?  I cant find iDVD in the search box or in finer.  Why would the macbook install imovie without installing iDVD too?  I need to burn my video off of iMovie so i need iDVD to do that for me.  Ive tried downloading i

    • Captivate 6 MP4 does not play in Quicktime 7.7.2

      When I published to MP4 using the YouTube HD or SD setting in Captivate 5.5, Quicktime 7.7.2 plays the video just fine. When I publish to MP4 using the YouTube HD or SD settings in Captivate 6, Quicktime 7.7.2 does not render the video correctly. It

    • Create BRF object and call in Webdynpro ABAP

      Hi, can you please let me know how can i create BRF obejects and call them in webdynpro ABAP in WDC. Thanks, Mahesh.Gattu

    • Airport does not stay connected

      I'm having a bit of an issue with Airport.  My first Airport Express router died so I just got a new one.  It is the latest version with the power cord.  Prior one plugged directly into surge protector (no cord). Here is the problem: I simply plugged