What's the advantage of making an inner class as static with Java?

后端 未结 6 1222
梦毁少年i
梦毁少年i 2020-12-13 18:21

I have an inner class in my Java class.

\"enter

When I run find bugs, it recom

6条回答
  •  醉梦人生
    2020-12-13 19:11

    We already have good answers, here are my 5 cents:

    Both static and non-static inner classes are used when we need to separate logical functionalities yet using the methods and variables of the outer class. Both of the inner classes have access to the private variables of the outer class.

    Advantages of static inner class: 1) static classes can access the static variables from outer class 2) static classes can be treated like an independent class

    Non-static inner class: 1) cannot use static members of the outer class 2) cannot be treated like an independent class

    public class NestedClassDemo {
        private int a = 100;
        int b = 200;
        private static int c = 500;
    
        public NestedClassDemo() {
            TestInnerStatic teststat = new TestInnerStatic();
            System.out.println("const of NestedClassDemo, a is:"+a+", b is:"+b+".."+teststat.teststat_a);
        }
    
        public String getTask1(){
            return new TestInnerClass().getTask1();
        }
    
        public String getTask2(){
            return getTask1();
        }
    
    
        class TestInnerClass{
            int test_a = 10;
    
            TestInnerClass() {
                System.out.println("const of testinner private member of outerlcass"+a+"..."+c);
            }
            String getTask1(){
                return "task1 from inner:"+test_a+","+a;
            }
        }
    
        static class TestInnerStatic{
            int teststat_a = 20;
    
            public TestInnerStatic() {
                System.out.println("const of testinnerstat:"+teststat_a+" member of outer:"+c);
            }
    
            String getTask1stat(){
                return "task1 from inner stat:"+teststat_a+","+c;
            }
        }
    
        public static void main(String[] args){
            TestInnerStatic teststat = new TestInnerStatic();
            System.out.println(teststat.teststat_a);
            NestedClassDemo nestdemo = new NestedClassDemo();
            System.out.println(nestdemo.getTask1()+"...."+nestdemo.getTask2());
        }
    }
    

    Accessing the static inner and non-static inner class from outside:

    public class TestClass {
        public static void main(String[] args){
            NestedClassDemo.TestInnerClass a = new NestedClassDemo().new TestInnerClass();
            NestedClassDemo.TestInnerStatic b = new NestedClassDemo.TestInnerStatic();
        }
    }
    

    The official java doc for static inner class can be found at https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

提交回复
热议问题