简体   繁体   中英

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

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM