Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we declare private local inner class inside a method?

Tags:

java

class

class outer
{
    public void outerfunction()
    {

        private class inner // Line-1
        {
                public void showinner()
                {
                    System.out.println("I am in Inner Class");

                }

        }

    }
}

Line-1 : This Line gives error.

I know if I write abstract or Final for class inner. then,it is fine. Why class inner can't be private ?

like image 734
S J Avatar asked Oct 20 '22 06:10

S J


1 Answers

A private class is visible to all the methods and nested classes in the same file. Normally you would think of private as narrowing the scope of use, but in this case using private you are broadening the scope of where is the class is visible in a way Java doesn't support.

Making the method private is the same as doing this

class outer {
      private class inner { // Line-1
          public void showinner() {
              System.out.println("I am in Inner Class");    
          }
      }

      public void outerfunction() {    

     }
}

Which looks fine until you consider that a nested class can use the values in it's outer context.

class outer {
    public void printInner() {
        // accessible in the same .java file because we made it private
        inner i = new inner();
        i.showInner(); // what should `x` be?
    }

    public void outerfunction(final int x) {    
         private class inner { // Line-1
              public void showinner() {
                  System.out.println("I am in Inner Class, x= " + x);    
              }
          }    
    }
}
like image 195
Peter Lawrey Avatar answered Oct 23 '22 02:10

Peter Lawrey