Java - No enclosing instance of type Foo is accessible

后端 未结 5 1122
再見小時候
再見小時候 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:44

    Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

     public class PQ {
    
        public static void main(String[] args) {
    
            // create dog object here
            Dog dog = new PQ().new Dog();
            //OR
            PQ pq = new PQ();
            Dog dog1 = pq.new Dog();
        }
    
        abstract class Animal {
            abstract void checkup();
        }
    
        class Dog extends Animal {
            @Override
            void checkup() {
                System.out.println("Dog checkup");
    
            }
        }
    
        class Cat extends Animal {
            @Override
            void checkup() {
                System.out.println("Cat Checkup");
    
            }
        }
    }
    

提交回复
热议问题