Inner Classes(Thinking in Java)

痛定思痛。 2021-11-10 00:04 416阅读 0赞

  If you want to make an object of the inner class anywhere except from within a non-static method of the outer class, you must specify the type of that object as OuterClassName.InnerClassName,

  So an inner class has automatic access to the members of the enclosing class. How can this happen? The inner class secretly captures a reference to the particular object of the enclosing class that was responsible for creating it. Then, when you refer to a member of the enclosing class, that reference is used to select that member.

  If you need to produce the reference to the outer-class object, you name the outer class followed by a dot and this. The resulting reference is automatically the correct type, which is known and checked at compile time, so there is no runtime overhead. Sometimes you want to tell some other object to create an object of one of its inner classes. To do this you must provide a reference to the other outer-class object in the new expression, using the .new syntax.

  Inner classes can be created within a method or even an arbitrary scope. There are two reasons for doing this:

  1.As shown previously, you’re implementing an interface of some kind so that you can create and return a reference.

  2.You’re solving a complicated problem and you want to create a class to aid in your solution, but you don’t want it publicly available.

  If you don’t need a connection between the inner-class object and the outerclass object, then you can make the inner class static. This is commonly called a nested class.2 To understand the meaning of static when applied to inner classes, you must remember that the object of an ordinary inner class implicitly keeps a reference to the object of the enclosing class that created it. This is not true, however, when you say an inner class is static. A nested class means:

  1.You don’t need an outer-class object in order to create an object of a nested class.

  2.You can’t access a non-static outer-class object from an object of a nested class.

Nested classes are different from ordinary inner classes in another way, as well. Fields and methods in ordinary inner classes can only be at the outer level of a class, so ordinary inner classes cannot have static data, static fields, or nested classes. However, nested classes can have all of these.

转载于:https://www.cnblogs.com/zhtf2014/archive/2010/01/26/1657054.html

发表评论

表情:
评论列表 (有 0 条评论,416人围观)

还没有评论,来说两句吧...

相关阅读

    相关 inner class

    > 可以将一个类的定义放在另一个类的定义内部,这就是内部类。       内部类是一个非常有用的特性但又比较难理解使用的特性(鄙人到现在都没有怎么使用过内部类,对内部类也只是

    相关 java 内部类(inner class)详解

    一、为何使用内部类 内部类提供了更好的封装,只有外部类能访问内部类 内部类可以独立继承一个接口,不受外部类是否继承接口影响 内部类中的属性和方法即使是外