Java nested classes 嵌套類

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

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


nested classes:oracle

1.static nested classes:this

 public class Outer{
      public class Nested{
      }
   }

   declare inner class:spa

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

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

 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;htm

   Outer outer = new Outer();ci

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

   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
相關文章
相關標籤/搜索