`
allwit
  • 浏览: 18767 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java Nested Classes

阅读更多

In Java you can define a class inside an other class.

A class can be nested:

  • inside another class,
  • or inside a method

Nest a class inside a class

When a class is declared inside another class, the nested class' access modifier can be public, private or package(default).

public class OuterClass
{
   private String outerInstanceVar;

   public class InnerClass
   {
      public void printVars()
      {
         System.out.println( "Print Outer Class Instance Var.:" + outerInstanceVar);
      }
   } 
}

The inner class has access to the enclosing class instance's variables and methods, even private ones, as seen above. This makes it very different from the nested class in C++, which are equivalent to the "static" inner classes, see below.

An inner object has a reference to the outer object. The nested object can only be created with a reference to the 'outer' object. See below.

public void testInner()
{
    ...
    OuterClass outer = new OuterClass();
    OuterClass.InnerClass inner = outer.new OuterClass.InnerClass();	
    ...
}

(When in a non-static method of the outer class, you can directly use new InnerClass(), since the class instance is implied to be this.)

You can directly access the reference to the outer object from within an inner class with the syntax OuterClass.this; although this is usually unnecessary because you already have access to its fields and methods.

Inner classes compile to separate ".class" bytecode files, usually with the name of the enclosing class, followed by a "$", followed by the name of the inner class. So for example, the above inner class would typically be compiled to a file named "OuterClass$InnerClass.class".

Static inner class

An inner class can be declared static. A static inner class has no enclosing instance, and therefore cannot access instance variables and methods of the outer class. You do not specify an instance when creating a static inner class. This is equivalent to the inner classes in C++.

Nest a class inside a method

These inner classes, also called local classes, cannot have access modifiers, like local variables, since the class is 'private' to the method. The inner class can be only abstract or final.

public class OuterClass
{
   public void method()
   {
      class InnerClass
      {
 
      } 
   }
}

In addition to instance variables of the enclosing class, local classes can also access local variables of the enclosing method, but only ones that are declared final. This is because the local class instance might outlive the invocation of the method, and so needs its own copy of the variable. To avoid problems with having two different copies of a mutable variable with the same name in the same scope, it is required to be final, so it cannot be changed.

Anonymous Classes

In Java a class definition and its instantiation can be combined into a single step. By doing that the class does not require a name. Those classes are called anonymous classes. An anonymous class can be defined and instantiated in contexts where a reference can be used, and it is a nested class to an existing class. Anonymous class is a special case of the local class to a method, above; and hence they also can use final local variables of the enclosing method.

Anonymous classes are most useful to subclass and upcast to an 'Adapter Class' or to an interface.

public interface ActionListener
{
    public void click();
}
...
ActionListener clk = new ActionListener() 
    {
        public void click()
        {
            // --- implementation of the click event ---
            ...
            return;
        }
    };

In the above example the class that implements the ActionListener is anonymous. The class is defined where it is instantiated.

The above code is harder to read than if the class explicitly defined, so why use it? If many implementations are needed for an interface and those classes are used only in one particular place, using anonymous class makes sense.

The following example uses anonymous class to implement an action listener.

import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
class MyApp implements Serializable
{
   BigObjectThatShouldNotBeSerializedWithAButton bigOne;
   Button aButton = new Button(); 
   MyApp()
   {
       aButton.addActionListener( new ActionListener()
           {
               public void actionPerformed(ActionEvent e)
               {
                   System.out.println("Hello There");
               }
           }
       );
   }
}

The following example does the same thing, but it names the class that implements the action listener.

import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
class MyApp implements Serializable
{
   BigObjectThatShouldNotBeSerializedWithAButton bigOne;
   Button aButton = new Button();
   // --- Nested class to implement the action listener ---
   class MyActionListener implements ActionListener
   {
       public void actionPerformed(ActionEvent e)
       {
           System.out.println("Hello There");
       }
   }
   MyApp()
   {
       aButton.addActionListener( new MyActionListener() );
   }
}

Using anonymous classes is especially preferable when you intend to use many different classes that each implement the same Interface.

分享到:
评论

相关推荐

    Java-Docs-3.zip_nested

    在Java编程语言中,"nested classes" 是一个重要的概念,特别是在面试中经常被问到。这个主题涵盖了内部类(inner classes)、静态嵌套类(static nested classes)以及其他相关的概念,这些都是理解和编写复杂Java...

    java代码-Nested

    在Java编程语言中,"Nested"通常指的是嵌套类或者嵌套结构,这是一门强大的特性,使得代码更加模块化和高效。嵌套类可以分为两种主要类型:内部类(Inner Classes)和局部类(Local Classes)。让我们深入探讨这两种...

    Java.7.A.Comprehensive.Tutorial

    Chapter 14 Nested and Inner Classes Chapter 15 Swing Basics Chapter 16 Swinging Higher Chapter 17 Polymorphism Chapter 18 Annotations Chapter 19 Internationalization Chapter 20 Applets Chapter 21 Java...

    Java简单讲义及习题

    Topics include: Object-oriented programming, primitives, arrays, objects, inheritance, interfaces, polymorphism, hashing, data structures, collections, nested classes, floating point precision, ...

    java嵌套类

    在Java语言中,嵌套类(Nested Classes)是Java语言规范中定义的术语,指的是在其他类或接口的主体内部声明的类。嵌套类可以细分为多种类型,每种类型都有其特点和使用场景。 首先,根据嵌套类定义的位置,可以将...

    Java for Programmers

    * Classes, Objects, Encapsulation, Inheritance, Polymorphism, Interfaces, Nested Classes * Integrated OOP Case Studies: Time, GradeBook, Employee * Industrial-Strength, 95-Page OOD/UML 2 ATM Case ...

    Java教学详细内容课件.ppt

    模块6:Nested Classes(嵌套类),涵盖了Java中的嵌套类概念,包括静态嵌套类、非静态嵌套类等内容。 模块7:Packages(包),涵盖了Java中的包概念,包括包的声明、导入包、包的使用等内容。 模块8:Exceptions...

    quaqua-3.9.5.nested

    **Swing** 是Java的一种图形用户界面(GUI)工具包,它是Java Foundation Classes (JFC)的一部分。Swing提供了一组可定制的组件,如按钮、文本框和表格,用于构建桌面应用程序。由于Swing是轻量级的,它不依赖于操作...

    解决jar发布时的出现D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static

    springboot获取根目录及资源路径及解决jar发布时的出现D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static,采用该工具类可在发布成jar时访问到资源文件路径地址

    java视频 static关键字

    5. **静态内部类(Static Nested Classes)**: `static`修饰的内部类是独立于其外部类的,不需要外部类的实例就能创建。它们类似于顶级类,但仍然保持与外部类的关联。 6. **静态工厂方法(Static Factory ...

    部分Java考试真题

    第二个问题涉及静态内部类(Static Nested Classes)。静态内部类不是外部类的实例成员,而是类成员,因此它们可以独立于外部类的实例存在。选项C正确:静态内部类不需要外部类的实例就可以被创建。静态内部类的实例...

    Java 课件

    4. **JAVA-L11-NestedClasses.ppt** - 内部类(Nested Classes)是指定义在另一个类内部的类。Java支持成员内部类、局部内部类、匿名内部类和静态内部类,它们可以增强代码的封装性和可读性,有时也能简化复杂的设计...

    100java金典编程实例源代码

     struts-nested.tld 63.14 KB  struts-template.tld 1.59 KB  struts-tiles.tld 7.67 KB  struts.jar 486.38 KB    实例56 (1 folders, 6 files, 10.96 KB, 1.96 MB in total.)  JDBCDataMeta.class 4.59 KB ...

    MLDN魔乐JAVA_10static关键字.rar

    5. **静态内部类(Static Nested Classes)**: 静态内部类不同于非静态(成员)内部类,它们不持有对外部类的隐式引用。这意味着静态内部类可以在没有外部类对象的情况下被实例化。它们通常用于封装与外部类相关但...

    Java学习笔记

    - **嵌套类(Nested Classes)**:在一个类的内部定义的类。 - **类修饰符** - **注解(Annotations)**:用于向编译器或其他工具提供元数据。 - **public**:公共修饰符,表示类及其公共成员对外部可见。 - ...

    Java 深入理解嵌套类和内部类

    Java 中的嵌套类和内部类是指在一个类的内部定义另一个类,这种类称为嵌套类(nested classes)。嵌套类有两种类型:静态嵌套类和非静态嵌套类。静态嵌套类使用很少,非静态嵌套类也即被称作为内部类(inner)。嵌套...

    Addison.Wesley.The.Java.Programming.Language.4th.Edition.Aug.2005.chm

    Chapter 5Nested Classes and Interfacesdescribes how classes and interfaces can be declared inside other classes and interfaces, and the benefits that provides. Finally, Chapter 6Enumeration ...

    java内部类的讲解

    1. **嵌套顶级类(Nested Top-Level Classes)**:这种内部类类似于普通的类,但它们被定义在另一个类的内部。它们没有访问外部类的实例变量或方法的能力,除非它们是静态的。嵌套顶级类可以通过外部类名访问。 2. ...

    java-guide:现代Java指南(Java 17)

    Java指南 现代Java指南(Java 17) ...nested_classes.md array.md Implementation_interface.md generics.md 包装器 方差 limit_of_generics.md stream.md collector.md data_structure.md sort.md 使用Jav

    SCJP Sun® Certified Programmer for Java™ 6 Study Guide chapter 8

    ### SCJP Sun® Certified Programmer for Java™ 6 Study Guide Chapter 8: Inner Classes #### 认证目标 在本章中,我们将深入了解Java中的内部类(Inner Classes),这是SCJP认证考试的重要部分之一。虽然没有...

Global site tag (gtag.js) - Google Analytics