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

java Nested Classes

阅读更多

复习下java基础时,发现关于内部类的资料都不是很全,特地找了一个,和大家分享。

Inner Classes

Inner classes let you define one class within another, they provide a type of scoping for your classes since you can make one class a member of another class. This web page discusses four types of inner class

  • Inner Class
  • Method-Local Inner Class
  • Anonymous Inner Class
  • Static Nested Class

Inner Class

Normally when you are programming a class should have code only for the things an object of that particular type needs to do, any other behavior should be part of another class better suited for that job. Sometimes though you design a class that has different behavior but also needs to be intimately tied to the class you're designing, for an example event handlers are best example of this. One of the key benefits of an inner class is the "special-relationship" an inner class instance shares with an instance of the outer class. That special-relationship gives code in the inner class access to members of the enclosing (outer) class, as if the inner class was a part of the outer class, this includes any private members as well. Inner classes are not static, method-local or anonymous they are just a regular class.

Inner Class

class OuterClass {
class InnerClass { }
}

Note: compiling the above will produce the below two files, you cannot run the OuterClass$InnerClass because a inner class cannot have a static declaration of any kind, you can only access the Inner class via the outer class.

OuterClass.class
OuterClass$InnerClass.class

Accessing private variables

class OuterClass {
private int x = 75;

public void makeInner() {
InnerClass in1 = new InnerClass;
in1.seeOuter();

// Inner Class
class InnerClass {
public void seeOuter() {
System.out.println("Private variable x is " + x);
}
}
}

Note: we can access the private member with no problems which is perfectly legal

The only rules regarding inner classes is that you must have an instance of the outer class to tie to the inner class. A inner class can accept the following access modifiers: final, abstract, public, private, protected, static and strictfp.

create a inner class object from outside the outer class instance

public static void main (String[ ] args) {
OuterClass mo = new OuterClass();
OuterClass.InnerClass inner = mo.new InnerClass();

// you could replace the above code with one line
// OuterClass.InnerClass inner = new OuterClass().new InnerClass();

inner.methodA();

}

referencing the Inner or Outer instance from within the inner class

class OuterClass {
int count = 10; // the outer class variable

class InnerClass {
int count = 5; // the inner class variable

void methodA() {
System.out.println("inner count " + this.count); // displays 5
System.out.println("outer count " + OuterClass.this.count); // displays 10
}
}
}

Method-Local Inner Class

A regular inner class is scoped inside another class curly braces, but outside any method code (in other words at the same level as instance variable is declared), but you can also define an inner class within a method.

Method-Local Inner class

class OuterClass2 {
private String x = "OuterClass2";

void doStuff() {
class InnerClass {
public void seeOuter() {
System.out.println("Outer x is " + x);
}
}

// You can only instantiate from within the method
InnerClass ic = new InnerClass(); // This line must come after the class line
ic.seeOuter();
}
}

Method-Local inner classes can only be instantiated from within the method where the inner class is defined (no where else). The inner class has no access to the local method variables because when the method completes all local variables are destroyed, but even after the method has gone the class may still be around and with no local method variables this would cause problems, however if the local variables are marked final then the class can use them.

Anonymous Inner Class

Anonymous Inner class are what they say they are class without a name, you can declare them within a method or as a argument to a method.

Anonymous Inner Class
(flavor one)

class TestFood {
public static void main(String [] args) {
Food f1 = new Food();
f1.p.pop(); // p is the anonymous class
}
}

class PopCorn {
public void pop() {
System.out.println("pop goes the corn");
}
}

class Food {
Popcorn p = new PopCorn() { // Notice no semi-colon but a backet instead, the start of the anonymous inner class
public void pop() { // override the superclass PopCorn's op method
System.out.println("anonymous popcorn");
}
}; // end of the anonymous class, note the semi-colon
}

Note: the anonymous class is of type subclass

Anonymous Inner Class
(flavor two)

interface Cookable {
public void cook();
}

class Food {
Cookable c = new Cookable() { // looks like you are instantiated a interface (not possible)
public void cook() {
System.out.println("anonymous Cookable implementer");
}
};
}

Note: the anonymous class is of type interface, also you can only implement one interface

Anonymous Inner Class
(flavor three)

class MyWonderfulClass {
void go() {
Bar b = new Bar();
b.doStuff(new Foo() { // implement the anonymous class as an argument
public void foof() {
System.outprintln("Foo interface implemented by annoymous class");
}
}); // end inner class def, argument and statement
}
}

interface Foo {
void Foo();
}

class Bar {
void doStuff(Foo f) { ... }
}

When using anonymous inner classes polymorphism is in play, you can only call methods on an anonymous inner class reference that are defined in the reference variable type, this is no different from any other polymorphic reference. Anonymous inner classes can only be of one type either a subclass or interface type.

One final note is that when anonymous classes are created the filename is usually something like Class$1.class, Class$2.class, etc

Static Nested Class

Static nested classes are sometimes refered to as static inner classes, they aren't inner classes at all, by the standard definition of an inner class. A static nested class does not have that special-relationship that inner classes have, they cannot access the instance methods or variables. The class is not static (a class cannot be static), the static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members without having an instance of the outer class.

Static Nested Class public class OuterClass {
static class Nested { ... }
}
Instantiating a Static Nested Class

class OuterClass {
static class Nested { ... }
}

class TestClass {
public static void main(String [] args) {
OuterClass.Nested n = new OuterClass.Nested();
}
}

 

 

refer to

http://www.datadisk.co.uk/html_docs/java/inner_classes.htm

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

分享到:
评论

相关推荐

    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