Search code examples
javaprivate-class

How to call a private local class


So, inside a bigger class, there is a local private class that i need to use for a method later on, but i don't know how to access it...

The private class, which i cannot change because it's part of the exercise, looks like this:

private class Counter 
 {
   String element;
   int frequency;             
   Counter (String element) 
   {
     this.element = element;
     frequency = 0;
   } 
   String element() {
       return this.element;
   }
 }

And the method I need to implement, which should add the Id with its frequency to the frequency list lf, looks like this:

private void update (String id, IList<Counter> lf) 
  {
      
  }

I´m trying to use the add method from the IList, but i don't know how to use a type Counter, since it is a privae class and I can't access it.


Solution

  • Assuming the following starting class (NO, it is not the solution):

    public class Bigger {
    
        // inner class should not be changed
        private class Counter {
            String element;
            int frequency;             
    
            Counter (String element) {
                this.element = element;
                frequency = 0;
            } 
    
            String element() {
                return this.element;
            }
        }
    
        private void update (String id, IList<Counter> lf) {
            // TODO 
        }
    }
    

    To access Counter inside of update, we can just write:

    public class Bigger {
        // ...
        private void update (String id, IList<Counter> lf) {
            Counter counter = new Counter(id);
            // eventually call counter.element()
            // or accessfields like counter.frequency = 1;
            // TODO 
        }
    }
    

    Note: Counter is not a local class, but an inner class (I assumed one, since local classes cannot be declared private).

    The access to private inner classes and even to private members of such classes from within the same containing class, is allowed by JLS 6.6.1:

    Otherwise, the member or constructor is declared private. Access is permitted only when the access occurs from within the body of the top level class or interface that encloses the declaration of the member or constructor.