21xrx.com
2025-04-19 07:32:19 Saturday
文章检索 我的文章 写文章
Java内部类:解释、四大作用及代码案例
2023-06-14 06:56:37 深夜i     18     0
Java内部类 封装 回调 多重继承 迭代器

Java内部类是一种定义在另一个类内部的类。内部类可以访问外部类的成员变量和方法,而且可以忽略访问控制符的限制。下面分别介绍Java内部类的四大作用及代码案例。

1. 封装内部类

当一个内部类只有外部类能够使用时,可以将内部类声明为private。例如:

public class Outer {
  private class Inner {
    private int innerValue;
    public Inner(int innerValue)
      this.innerValue = innerValue;
    
    public void printOuterValue() {
      System.out.println("Outer value is " + Outer.this.outerValue);
    }
  }
  private int outerValue;
  public Outer(int outerValue)
    this.outerValue = outerValue;
  
  public void printInnerValue() {
    Inner inner = new Inner(10);
    System.out.println("Inner value is " + inner.innerValue);
  }
}

2.实现回调

内部类可以实现回调,即当事件发生时,内部类会自动调用外部类的方法。例如:

public class Event {
  private OnEventListener listener;
  public void setListener(OnEventListener listener)
    this.listener = listener;
  
  public void doEvent() {
    if (listener != null) {
      listener.onEvent();
    }
  }
  public interface OnEventListener {
    void onEvent();
  }
}
public class Outer implements Event.OnEventListener {
  private Event event;
  public Outer() {
    event = new Event();
    event.setListener(this);
  }
  public void onEvent() {
    System.out.println("Event happened in outer class");
  }
}

3. 实现多重继承

Java只允许单继承,但是内部类可以实现多重继承。例如:

public interface A {
  void methodA();
}
public interface B {
  void methodB();
}
public class C {
  public void methodC() {
    System.out.println("methodC");
  }
}
public class Outer {
  private class Inner extends C implements A, B {
    public void methodA() {
      System.out.println("methodA");
    }
    public void methodB() {
      System.out.println("methodB");
    }
  }
  public void test() {
    Inner inner = new Inner();
    inner.methodA();
    inner.methodB();
    inner.methodC();
  }
}

4. 实现迭代器

内部类可以用来实现迭代器。例如:

public class MyList {
  private int[] array = 4;
  public Iterator getIterator() {
    return new MyIterator();
  }
  private class MyIterator implements Iterator {
    private int cursor = 0;
    public boolean hasNext()
      return cursor < array.length;
    
    public Object next() {
      if (cursor < array.length) {
        return array[cursor++];
      }
      return null;
    }
    public void remove() {
      throw new UnsupportedOperationException();
    }
  }
}
public class Outer {
  public static void main(String[] args) {
    MyList list = new MyList();
    Iterator iterator = list.getIterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

  
  

评论区