嵌套类,内部类,匿名内部类再学习

内部类

在一个类内声明的类称为内部类。

内部类“隐式”地持有外部类的引用,所以可以访问外部类对象的成员,方法。

看下Oracle给的一个例子。

public class DataStructure {

    // Create an array
    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        // fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }

    public void printEven() {

        // Print out values of even indices of the array
        DataStructureIterator iterator = this.new EvenIterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }

    interface DataStructureIterator extends java.util.Iterator<Integer> { }

    // Inner class implements the DataStructureIterator interface,
    // which extends the Iterator<Integer> interface

    private class EvenIterator implements DataStructureIterator {

        // Start stepping through the array from the beginning
        private int nextIndex = 0;

        public boolean hasNext() {

            // Check if the current element is the last in the array
            return (nextIndex <= SIZE - 1);
        }

        public Integer next() {

            // Record a value of an even index of the array
            Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);

            // Get the next even element
            nextIndex += 2;
            return retValue;
        }
    }

    public static void main(String s[]) {

        // Fill the array with integer values and print out only
        // values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }
}

内部类可以作外部类的Helper类,如上面的例子。


匿名类

匿名类即没有类名,因为不需要多次创建一个类的对象,只需要该类的一个对象,这时就可以使用匿名类。

而匿名类也是内部类。

 addWindowListener( 
     new WindowAdapter() {
         public void windowClosing( WindowEvent e ) {
             System.exit(0); 
         } 
     });
上面的匿名类和下面的内部类是一致的。

public class WindowClosingAdapter extends WindowAdapter {
     public void windowClosing( WindowEvent e ) {
         System.exit(0);
     } 
 }

 ...

 addWindowListener( new WindowClosingAdapter() );
所以,也称匿名内部类。

匿名内部类把类声明和类的初始化作为一个表达式放在一行完成

匿名内部类也持有外部类对象的引用,可以调用其属性和方法。

内部类,匿名类访问外部类的局部变量,需要将局部变量用final修饰。


静态内部类

静态内部类不需要外部类的引用,普通内部类持有外部类的引用,有可能会导致外部类无法被GC回收而导致内存泄漏,这时使用静态内部类就可以避免这个问题。

嵌套类

java允许在一个类内定义另外的类。

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
}

嵌套类分2种:静态嵌入类,也称静态内部类;非静态嵌入类,常称内部类。

嵌套类是外部类的成员(member),非静态内部类可以访问外部类的成员,即使是private的,静态内部类则不能。嵌套类可以用public,protected,private修饰。

内部类可看作是外部类的实例成员,静态内部类可看作外部类的静态成员,认识到这个就能理解为什么静态内部类可以访问外部类的成员,而静态内部类却不能。


什么时候使用嵌套类,有什么好处?

  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

局部类和匿名类是2种特殊的内部类!


发现学习Java最好的方式可能是阅读Oracle的官方文档,对嵌套类,内部类,匿名内部类之前看过不少介绍的文章,却一直没有搞清楚(当然现在也不一定真的弄清楚了),但这次看了官方文档,有原理解析,有示例代码,弄清了很多东西。

嵌套类  匿名类





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值