Java - No enclosing instance of type Foo is accessible

后端 未结 5 1148
再見小時候
再見小時候 2020-11-21 06:35

I have the following code:

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public stat         


        
5条回答
  •  一个人的身影
    2020-11-21 06:47

    Well... so many good answers but i wanna to add more on it. A brief look on Inner class in Java- Java allows us to define a class within another class and Being able to nest classes in this way has certain advantages:

    1. It can hide(It increases encapsulation) the class from other classes - especially relevant if the class is only being used by the class it is contained within. In this case there is no need for the outside world to know about it.

    2. It can make code more maintainable as the classes are logically grouped together around where they are needed.

    3. The inner class has access to the instance variables and methods of its containing class.

    We have mainly three types of Inner Classes

    1. Local inner
    2. Static Inner Class
    3. Anonymous Inner Class

    Some of the important points to be remember

    • We need class object to access the Local Inner Class in which it exist.
    • Static Inner Class get directly accessed same as like any other static method of the same class in which it is exists.
    • Anonymous Inner Class are not visible to out side world as well as to the other methods or classes of the same class(in which it is exist) and it is used on the point where it is declared.

    Let`s try to see the above concepts practically_

    public class MyInnerClass {
    
    public static void main(String args[]) throws InterruptedException {
        // direct access to inner class method
        new MyInnerClass.StaticInnerClass().staticInnerClassMethod();
    
        // static inner class reference object
        StaticInnerClass staticInnerclass = new StaticInnerClass();
        staticInnerclass.staticInnerClassMethod();
    
        // access local inner class
        LocalInnerClass localInnerClass = new MyInnerClass().new LocalInnerClass();
        localInnerClass.localInnerClassMethod();
    
        /*
         * Pay attention to the opening curly braces and the fact that there's a
         * semicolon at the very end, once the anonymous class is created:
         */
        /*
         AnonymousClass anonymousClass = new AnonymousClass() {
             // your code goes here...
    
         };*/
     }
    
    // static inner class
    static class StaticInnerClass {
        public void staticInnerClassMethod() {
            System.out.println("Hay... from Static Inner class!");
        }
    }
    
    // local inner class
    class LocalInnerClass {
        public void localInnerClassMethod() {
            System.out.println("Hay... from local Inner class!");
        }
     }
    
    }
    

    I hope this will helps to everyone. Please refer for more

提交回复
热议问题