我是 Android 编程新手,对以下代码没有什么困惑。 这部分代码来自android开发者网站:
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_SUBTITLE = "subtitle";
...
}
}
我在 Java 文档和其他一些博客中阅读了一些有关嵌套类的文章,并了解了使用嵌套类的以下原因:
- 提供更好的封装。
- 如果一个类只与另一个类相关,那么我们最好制作这两个类的嵌套类。
但是在这里,我想不出任何可以使用嵌套类的东西。
创建嵌套类的目的到底是什么?
最佳答案
这个特定的嵌套类用作与其主类相关的String
常量的命名空间。
- 它是
抽象
,因此不适合实例化 - 它实现了
BaseColumns
接口(interface),该接口(interface)本质上是一种将字符串常量“转储”到FeedEntry
类中的方法
Why did they used nested class instead of free-standing class?
使用嵌套类强调内部类与其外部类的“语义接近性”。它向代码的读者传达了 FeedEntry
只能在 FeedReaderContract
上下文中进行解释。否则,FeedEntry
就没有意义。本质上,这是为代码的人类读者完成的,因为在这种情况下,编译器不会有任何区别。
关于java - 该嵌套类的实际目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31002706/