Java nested classes 嵌套类

你。 提交于 2019-12-04 17:03:06

quoted from :http://tutorials.jenkov.com/java/nested-classes.html;

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html


nested classes:

1.static nested classes:

 public class Outer{
      public class Nested{
      }
   }

   declare inner class:

   Outer.Nested instance = new Outer.Nested();

2.Non-static nested classes(Inner Classes):

 public class Outer{
      private String text = "I am a string!";      
      public class Inner{
         public void printText() {
               System.out.println(text);
        }
      }
   }

   ① declaration;② call the printText() method;

   Outer outer = new Outer();

   Outer.Inner inner = new Outer.Inner();

   inner.printText();

special inner class: local classes;  anonymous classes

3.shadowing:

public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

The following is the output of this example:

x = 23
this.x = 1
ShadowTest.this.x = 0



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!