且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java内部类扩展外部类

更新时间:2022-11-23 13:58:09

看看Java的

Have a look at Java's Point2D. It has two inner classes that are sub-classes of it.

要注意的重要一点是它们是static内部类.这与常规内部类完全不同.就像静态方法一样,静态类是在类级别而不是对象级别定义的.

The important thing to note is that they are static inner classes. This has an entirely diffenent meaning that a regular inner class. Just like a static method, a static class is defined at the class-level instead of the object level.

Point2D情况下,已完成逻辑上耦合类及其逻辑的操作.它可以帮助abstract类型Point2D的用户找到他们可以使用的实现.

In the Point2D case, it is done to logically couple the classes and their logic. It helps a user of the abstract type Point2D find an implementation that they can use.

为回应您的编辑,我想指出1个重要的事实.一个Java文件只能包含一个公共类,对于公共内部类,除外.尽管您的两个示例都可以编译,但它们不允许公众访问这些类.如果要在单个文件中向某人展示多个公共类,则必须使用公共静态内部类.

In response to your edit I'd like to point out 1 important fact. A single Java file may only contain one public class, except for public inner classes. While both of your examples may compile, they do not allow access to those classes to the public. If you want to present multiple public classes to someone in a single file, you must use public static inner classes.