1. 程式人生 > 其它 >Java 成員內部類

Java 成員內部類

  

package com.gibe;

public class Ersatz {
  public static void main(String[] args) {
    // 外部其他類, 使用成員內部類三種方法
    Outer outer = new Outer();
    outer.mm();
    // 外部instance.new
    Outer.Inner inner = outer.new Inner();
    inner.say();
    // 外部類編寫物件方法, 返回Inner物件
    Outer.Inner instance = outer.getInstance();
    instance.say();
    //
    Outer.Inner vv = new Outer().new Inner();
    vv.say();
  }
}

class Outer {
  private int n = 11;
  public String name = "Outer";

  private void hi(Inner inner) {
    System.out.println("Outer hi()");
    System.out.println("inner: "+inner);
  }

  private static final void m() {
    System.out.println("Outer static m()");
  }

  public final class Inner {
    private double salary = 99.8;
    private int n = 22;

    public Inner() {
      System.out.println(this);
    }

    public void say() {
      System.out.println("n=" + n + " Outer.this.n=" + Outer.this.n);
      hi(this);
      m();
    }
  }

  public Inner getInstance() {
    return new Inner();
  }

  public void mm() {
    Inner inner = new Inner();
    inner.say();
  }
}