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.

Similar Messages

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

  • How to clear a private static class attribute once it's been created?

    <pre>I'm working with an instance of a complex Class object that has been created using the function module <br>HRXSS_CAT_APPLICATION_INIT. The Class object that I am trying to work with is<br> CL_XSS_CAT_BUSINESS_LAYER and in particular its Static Private component attribute PROFILE.<br>
    The issue that I am having is that the first call of this function module creates and populates the Static Private component attribute, <br>PROFILE, for the instance of this Class and I do not know how to initialize it once it's been created. The PROFILE attribute is an <br>object reference to an instance of Class CL_XSS_CAT_PROFILE. <br>
    I want to reset/intialize this Static Private component. I can then call a Class Method with<br> different parameters so that it repopulates PROFILE with different attributes. <br>There is no Public method to do this in CL_XSS_CAT_BUSINESS_LAYER and even the Private method<br> INIT_PROFILE, the logic first checks to see if the PROFILE component is initial before creating a new PROFILE<br> object instance. All the Attributes of the CL_XSS_CAT_PROFILE object are Static and Private.
    <br>
    I would appreciate any insight anyone might have in how to reset/initialize this Class component attribute.<br><br>
    Thanks much,<br>
    <br>
    Graham<br>
    Sample code snippet is as follows:
    <br><br>
    DATA: lr_cats_application_rfc TYPE REF TO IF_XSS_CAT_APPLICATION_RFC,
    lr_core TYPE REF TO IF_XSS_PT_APPLICATION_CORE,
    lr_core TYPE REF TO CL_XSS_CAT_1_APPLICATION_CORE,
    lr_instance TYPE REF TO CL_XSS_CAT_APPLICATION,
    lr_business_layer TYPE REF TO CL_XSS_CAT_BUSINESS_LAYER,
    lr_profile TYPE REF TO CL_XSS_CAT_PROFILE,
    lr_profile_temp TYPE REF TO cl_xss_cat_profile.
    DATA: l_employee TYPE pernr_d.
    DATA: l_employee_tab TYPE rhxss_cat_employee_t.
    CASE im_command.
    WHEN 'DATESELECTION_PRVPERIOD'.
    *-> navigate to object component reference for CL_XSS_CAT_PROFILE instance
    lr_cats_application_rfc = im_ref_to_parameter_cache->REF_TO_APPLICATION.
    *-> navigate to object component reference for CL_XSS_CAT_1_APPLICATION_CORE
    lr_core ?= lr_cats_application_rfc->get_core( ).
    *-> navigate to object component reference for CL_XSS_CAT_BUSINESS_LAYER
    lr_business_layer = lr_core->business_layer.
    *-> navigate to object component reference for CL_XSS_CAT_PROFILE
    lr_profile = lr_business_layer->get_profile( ).
    l_employee = im_ref_to_parameter_cache->pernr.
    append l_employee to l_employee_tab.
    <br><br>
    *THIS IS WHERE I AM HAVING ISSUES...I WOULD LIKE TO CLEAR/INITIALIZE THE STATIC PRIVATE COMPONENT<br> LR_BUSINESS_LAYER->PROFILE BEFORE CALLING THE METHOD INITIALIZE_FOR_TIME_RECORDING<br>
    <br>
    <br><br>*THE FOLLOWING LINE FAILS ON A SYNTAX CHECK WITH 'FIELD "PROFILE" IS UNKNOWN. IT IS NEITHER IN <br>ONE OF THE *SPECIFIED TABLES NOR DEFINED BY A "DATA" STATEMENT
    <br>
    clear: lr_business_layer->profile.
    CALL METHOD lr_business_layer->initialize_for_time_recording
    EXPORTING
    im_employee_tab = l_employee_tab
    im_profile_id = 'MODAPPR1'
    im_startdate = sy-datum
    EXCEPTIONS
    pernr_not_enqueued = 1
    no_pernr_for_user_found = 2
    profile_not_found = 3.</pre>
    Edited by: Matt on Aug 1, 2009 12:44 PM

    OK...I apologize but I did not dig deep enough to see that the Enhancement Framework allows for the addition of Methods to Classes/Interfaces. Most of this ABAP OO stuff is still quite new to me so I'm struggling with syntax and what is and isn't possible based on how everything is declared. I guess now that I know I can do this I am having some problems understanding how singleton Class objects work and how to 'reset' them.
    The Class instance based on CL_XSS_CAT_BUSINESS_LAYER has a Static Private attribute PROFILE that is an object reference to the singleton Class instance CL_XSS_CAT_PROFILE.
    The singleton Class instance of CL_XSS_CAT_PROFILE has all of its attributes set to Static Private. If you look at this Class in SE80 you see that one of its attributes is also called PROFILE and is an object reference variable to itself.
    So the issue I am having is how to go about 'initializing' this singleton object so that I can 'recreate' this singleton object using a copy of the existing S
    I used the enhancement framework to create a copy of the CL_XSS_CAT_BUSINESS_PROFILE Instance Private Method INIT_PROFILE , called in INIT_PROFILE2, but I am not sure how to 'clear/reset' the instance of the CL_XSS_CAT_PROFILE object.
    Since PROFILE is an attribute of the CL_XSS_BUSINESS_LAYER object, I thought that a simple CLEAR PROFILE would reset the object but this is not the case. Within this method the FREE clears the value of the reference variable PROFILE but as soon as you step into the method me->init_profile, the value of PROFILE goes back to what it was. I need for all of the CL_XSS_CAT_PROFILE instance attributes to be reset or initialized so I can fill them again. I think I'm getting confused on the scope of things...should I be enhancing the CL_XSS_CAT_PROFILE Class with 'setter' methods so I can initialize all of the Static Private attributes that way instead of trying to clear all the attributes at a higher call level?
    Any assistance with helping me with my thought process or approach to this would be much appreciated.
    METHOD INIT_PROFILE2.
    FREE PROFILE.  >>> is reset but it does not carry through to next method call and does not clear all the attributes of the object referenced in PROFILE
    CALL METHOD me->init_profile
    EXPORTING
    IM_PROFILE_ID = im_profile_id
    etc...

  • Best practice regarding package-private or public classes

    Hello,
    If I was, for example, developing a library that client code would use and rely on, then I can see how I would design the library as a "module" contained in its own package,
    and I would certainly want to think carefully about what classes to expose to outside packages (using "public" as the class access modifier), as such classes would represent the
    exposed API. Any classes that are not part of the API would be made package-private (no access modifier). The package in which my library resides would thereby create an
    additional layer of encapsulation.
    However, thus far I've only developed small applications that reside in their own packages. There does not exist any "client code" in other packages that relies on the code I've
    written. In such a case, what is the best practice when I choose to make my classes public or package-private? Is it relevant?
    Thanks in advance!

    Jujubi wrote:
    ...However, thus far I've only developed small applications that reside in their own packages. There does not exist any "client code" in other packages that relies on the code I've
    written. In such a case, what is the best practice when I choose to make my classes public or package-private? Is it relevant?I've always gone by this rule of thumb: Do I want others using or is it appropriate for others to use my methodes. Are my methods "pure" and not containing package speicific coding. Can I guarentee that everything will be initialized correctly if the package is included in other projects.
    Basically--If I can be sure that the code will do what it is supposed to do and I've not "corrupted" the obvious meaning of the method, then I usually make it public--otherwise, the outside world, other packages, does not need to see it.

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

  • Private static nested class

    Hi everyone,
    I'm practicing nested classes. I've written this simple class:
    public class OuterClass {
      private static class InnerClass {
         private InnerClass() {
            System.out.println("in constructor" }
    } and another simple class to test:
    public class TestClass {
      public static void main(String[] args) {
            OuterClass.InnerClass in=   new OuterClass.InnerClass();
    }All classes compile and main method runs with no problem. Now I wonder what is the meaning of the private modifier here ??
    Thanks

    Ok, I'm using Oracle's JDeveloper 3.2 ( jdk1.2.2). The code I posted compiles and runs with no errors in Jdeveloper.
    However, I tested this on the command line ( using javac directly ) and it does not compile !

  • Private static SearchTree empty = empty();

    hi
    i have a problem understanding why modifying a particular line of code from its original form to another form does not compile.
    Original Statement:
    private static SearchTree empty = empty();
    The way I Modified it to:
    private static SearchTree empty;
    empty = empty();
    I get compilation errrors but the program executes. I have explained the same at the end of the code listing.
    class NodeTree extends SearchTree {
        private Comparable data;  // the data item at the root
        private SearchTree left;  // the left subtree
        private SearchTree right; // the right subtree
        //private = accessible to members only within the package
        <b>private static SearchTree empty = empty(); </b>
         * This class ought not to be instantiated directly
         //this constructor is used to instantiate a new NodeTree Object
         //which contains a left 'SearchTree', a right 'SearchTree'
         //and a data item
        protected NodeTree(Comparable item) {
            data = item;
            left = empty;
            right = empty;
        public boolean isEmpty() {
            return false;
        public int nrNodes() {
            return left.nrNodes() + right.nrNodes() + 1;
        public boolean contains(Comparable item) {
            int compare = item.compareTo(data);
            if (compare < 0) {
                return left.contains(item);
            } else if (compare > 0) {
                return right.contains(item);
            } else {
                return true;
        //t = t.add(new Integer(item)); // 40
        public SearchTree add(Comparable item)
             //the compareTo() method returns an integer
             //depending on the result of comparison
             //Here the comparison is being carried out
             //between 'this' which is nothing but 'item'
             //and 'data'
            int compare = item.compareTo(data);
            //compareTo returns and integer that is 0 if the
            // object is less than 'this', 1 if both are equal
            //and a positive integer if greater
            if (compare < 0) {
                left = left.add(item);
            } else if (compare > 0) {
                right = right.add(item);
            return this;
            //here the 'this' refers to the NodeTree obejc
        /* private method for use in public method <remove>
         * returns smallest item in non-empty tree
        private Comparable findMin() {
            if (left.isEmpty()) {
                return data;
            } else {
                return ((NodeTree) left).findMin();
        /* private method for use in public method <remove> 
         * removes node containing smallest item in non-empty tree
        private SearchTree removeMin() {
            if (left.isEmpty()) {
                return right;
            } else {
                left = ((NodeTree) left).removeMin();
                return this;
        public SearchTree remove(Comparable item) {
            int compare = item.compareTo(data);
            if (compare == 0 && right.isEmpty()) {
                return left;
            } else {
                if (compare < 0) {
                    left = left.remove(item);
                } else if (compare > 0) {
                    right = right.remove(item);
                } else { // compare == 0 and !right.isEmpty()
                    data = ((NodeTree) right).findMin();
                    right = ((NodeTree) right).removeMin();
                return this;
        public Enumeration elementsLevelOrder() {
            return new Enumeration() {
                private Queue q = new QueueArray();
                { // initialise the queue
                    q.enqueue(NodeTree.this);
                public boolean hasMoreElements() {
                    return !q.isEmpty();
                public Object nextElement() {
                    NodeTree root = (NodeTree) q.dequeue();
                    if (!root.left.isEmpty()) {
                        q.enqueue(root.left);
                    if (!root.right.isEmpty()) {
                        q.enqueue(root.right);
                    return root.data;
        // a class of objects to stack for in-order traversals
        // would also serve for PreOrder and PostOrder if required
        private class StackItem {
            NodeTree root; // the subtree we are currently processing
            boolean ready; // whether we are ready to return its root data
            StackItem(NodeTree root, boolean ready) {
                this.root = root;
                this.ready = ready;
        public Enumeration elementsInOrder() {
            return new Enumeration() {
                private Stack s = new StackArray();
                { // initialise the stack      
                    s.push(new StackItem(NodeTree.this, false));
                public boolean hasMoreElements() {
                    return !s.isEmpty();
                public Object nextElement() {
                    StackItem next = (StackItem) s.pop();
                    while (!next.ready) {
                        NodeTree root = next.root;
                        if (!root.right.isEmpty()) {
                            s.push(new StackItem((NodeTree) root.right, false));
                        // relocate the next line to get PreOrder or PostOrder
                        s.push(new StackItem(root, true));
                        if (!root.left.isEmpty()) {
                            s.push(new StackItem((NodeTree) root.left, false));
                        next = (StackItem) s.pop();
                    return next.root.data;
        public String toString() {
            String string = "";
            if (!left.isEmpty() && !right.isEmpty()) {
                string += "(" + left + " " + data + " " + right + ")";
            } else if (!left.isEmpty()) {
                string += "(" + left + " " + data + " .)";
            } else if (!right.isEmpty()) {
                string += "(. " + data + " " + right + ")";
            } else {
                string += data;
            return string;
    I tried to rewrite the following line ( the one that is made bold) in a different way as below:
    Original Statement:
    private static SearchTree empty = empty();
    Modified:
    private static SearchTree empty;
    empty = empty();
    and this does not work:
    the following errors were given by the compiler:
    D:\Documents and Settings\ilango\Desktop\javanotes\SearchTreeDemo.java:236: <identifier> expected
    empty = empty();
    ^
    D:\Documents and Settings\ilango\Desktop\javanotes\SearchTreeDemo.java:236: cannot resolve symbol
    symbol : class empty
    location: class DataStructures.NodeTree
    empty = empty();
    ^
    2 errors
    Process completed.
    But suprisingly the program runs perfectly. I get the desired output.
    I may be naive on this, but could somebody explain what's going on.
    thanks in advance

    You cannot write static code like this in your class,
    since the compiler has no idea that this is static code or variable-initialisation.
    Try the following:
    private static SearchTree empty;
        empty = empty();
    }This introduces a block of static code to be run at the loading and initialisation of the class.
    You could add more lines of code in this static-block.
    kind regards,

  • Private static MyInnerClass extends OtherClass + protected methods

    Hi!
    Consider this case:
    public class A {
    private static class A1 extends B {
    // this would resolve the error:
    //       protected static void b() { B.b(); }
    void a() { A1.b(); } // ERROR: B.b() is inaccessible
    public class B {
    protected static void b() {}
    }(Where A and B are in different packages.)
    Why is B.b() inaccessible here?
    A1 extends B, so it sees its protected methods.
    A is a nesting class of A1, so it sees the protected methods of A1.
    What am I missing here?
    Thank you!
    Agoston

    OK, my mistake, I missed the part about different
    packages.
    However the following further inner class of A
    compiles for me:
         private static class A2 extends A1
              A2()
                   b();
                   A1.b();
         }using the OP's original code without A1.b().That's what I was talking about: b() can be called from children, but not from the nesting class.
    >
    The statement quoted from the JCP exam is not
    correct. The inherited protected member is available
    to subclasses of A1, so the protected member
    b() doesn't 'become private' at all. It stays as is
    was, i.e. protected, i.e. accessible within the
    original package or to subclasses.If it stays protected, why can't the nesting class see it? (Once again, a protected method defined in A1 and not inherited from B is visible from A.)
    It seems as if the inherited protected method teleports into some mysterious realm of visibility levels between private and protected. (I.e. it's like protected, only from a nesting class it's seen as super-private - since the nesting class should even be able to see the private methods of its inner class, shouldn't it?)
    This whole inconsequent behavior on the part of the compiler feels like a huge bug to me.
    Nothing changes.Unfortunately. :)
    Agoston

  • Why a base class cannot be a Private or Protected ?????

    why a base class cannot be a Private or Protected ?????

    why a base class cannot be a Private orProtected
    ?????Who would be able to access it? (Assuming "base"
    means top-level class.)Private, none. Protected, all classes in same package
    and subclasses (as with the methods).
    Actually, its somewhat illogical that a class be
    declared package-private, but not protected, since
    protected is less restrictive.having a protected class would make no sense. subclasses are not permitted to lessen the protection of members of their superclass, so you'd end up with a class that nothing could use, except subclasses that in turn nothing else could use

  • Compiler bug with generics and private inner classes

    There appears to be a bug in the sun java compiler. This problem was reported against eclipse and the developers their concluded that it must be a problem with javac.
    Idea also seems to compile the example below. I couldn't find a bug report in the sun bug database. Can somebody tell me if this is a bug in javac and if there is a bug report for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=185422
    public class Foo <T>{
    private T myT;
    public T getT() {
    return myT;
    public void setT(T aT) {
    myT = aT;
    public class Bar extends Foo<Bar.Baz> {
    public static void main(String[] args) {
    Bar myBar = new Bar();
    myBar.setT(new Baz());
    System.out.println(myBar.getT().toString());
    private static class Baz {
    @Override
    public String toString() {
    return "Baz";
    Eclipse compiles and runs the code even though the Baz inner class is private.
    javac reports:
    Bar.java:1: Bar.Baz has private access in Bar
    public class Bar extends Foo<Bar.Baz>
    ^
    1 error

    As I said in my original post its not just eclipse that thinks the code snippet is compilable. IntelliJ Idea also parses it without complaining. I haven't looked at the java language spec but intuitively I see no reason why the code should not compile. I don't think eclipse submitting bug reports to sun has anything to do with courage. I would guess they just couldn't be bothered.

  • Calling package private method

    Suppose you have a class called A:
    org.blah.A
    |
    --org.blah.blahblah.B
    (B extends A)
    But class B is in another package than A
    So if I do the following
    A a = new A();
    B b = (B) a;and if class B has package private methods how can I call them by downcasting to B? What is a work-around?

    Tutorial:
    public is the most generous of the four modifiers. A public class, method, or variable may be used in any Java program without restriction.
    private is the most restrictive of the modifiers. A private variable or method may only be used by an instance of the class that declares the item.
    (read none) is the friend or default modifier. A class's default feature is available to any class in the same package.
    protected vars and methods are available to all classes in the same package as the class that declares them. Moreover, they are available to subclasses of the declaring class even if the subclass resides in a different package.

  • Private static ArrayList within java.util.Arrays

    I was recently reviewing the code in java.util.Arrays (class version 1.45 - Java version 1.4.1). Beginning on line 2289 is a private static class named ArrayList. I'm completely baffled as to why the author created this slimmed-down private class (which would be, incidentally, returned by the Arrays.asList(Object[] a) method) rather than use the public class java.util.ArrayList. Can anyone offer an explanation?
    Thanks,
    John

    from JDK JAVADoc:
    asList
    public static List asList(Object[] a)
    Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable.
    So the private ArrayList extends java.util.ArrayList, and any changes made this list does not affect the internal Object[].... in other words can not be changed.

  • Question regarding palcing cache related classes into a package

    Hi all,
    I have a question regarding placing classes into packages. Actually I am writing cache feature which caches the results which were evaluated previously. Since it is a cache, I don't want to expose it outside because it is only for internal purpose. I have 10 classes related to this cache feature. All of them are used by cache manager (the manager class which manages cache) only. So I thought it would make sense if I keep all the classes into a separate package.
    But the problem I have is, since the cache related classes are not exposed outside so I can't make them public. If they are not public I can't access them in the other packages of my code. I can't either make it public or private. Can someone suggest a solution for my problem?

    haki2 wrote:
    But the problem I have is, since the cache related classes are not exposed outside so I can't make them public. If they are not public I can't access them in the other packages of my code.Well, you shouldn't access them in your non-cache code.
    As far as I understand, the only class that other code needs to access is the cache manager. That one must be public. All other classes can be package-private (a.k.a default access). This way they can access each other and the cache manager can access them, but other code can't.

  • Static class

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

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

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

Maybe you are looking for

  • Can't use "Copy Finder Items" after "Run Workflow"

    Create a simple Automator workflow: Set just 1 action "Create Thumbnail Images" and save it. I called it "wf1.workflow". Now create the second workflow with 3 actions: "Get Specified Finder Items" action (choose an image file here). -> "Run Workflow"

  • Isolated Wave too small to work with, how do I increase size

    I use wave files I record myself. In the old version of Garageband when I double clicked on the wave in the track window it came up larger and editable. Now it comes up too small and impossible to work with. How can I increase the size of the wave?

  • Large image on small monitor

    Can one control image size? My iMac has a 17" monitor and occasionally a web image presents as way too big -- just a part is shown, with slide controls offered below and to the right. Any way to reduce the image to fit the monitor?

  • Help Required Email setting save to mass storage -...

    HI, I am using Nokia 701, The current setting of my phone is such that all the incomming and sent mails are saved in the phone memory. This creates problem and I have to delete the mails vary frequently from the phone. Please help me to save my email

  • Infotype for Clockin Application

    Hi  Experts, -> What is the Infotype used for simple clockin application where user has to click clockin for attendance in portal and the corresponding record to be updated in TEVEN ( The application is built using WebDynpro) ? -> What are the basic