- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 601字
- 2021-06-11 13:05:23
Inner Classes
Classes, as we have seen so far, cannot be hidden to other parts of the program. In code terms, they cannot be made private. To offer this kind of security mechanism, Java developed so-called inner classes. This type of class is declared nested within other classes. A quick example of this follows:
Example16.java
1 class Container {
2 // inner class
3 private class Continent {
4 public void print() {
5 System.out.println("This is an inner class");
6 }
7 }
8
9 // method to give access to the private inner class' method
10 void printContinent() {
11 Continent continent = new Continent();
12 continent.print();
13 }
14 }
The result of the previous example is:
This is an inner class
Process finished with exit code 0
The previous example is a case of a non-static inner class. There are two more: method-local inner classes (these are defined inside a method) and anonymous classes. There is no big difference in how method-local classes are declared in comparison to what you've seen so far. A method-local inner class's main characteristic is that it is defined only for the scope of that method; it cannot be called by other parts of the program.
When it comes to anonymous inner classes, they make for an interesting case that deserves to be studied. The reason for their existence is to make code more concise. With anonymous classes, you declare and instantiate the class at the same time. This means that for such a class, only one object is created. Anonymous classes are typically created by extending existing classes or interfaces. Let's look at an example defining one of these specific types of anonymous classes:
class Container {
int c = 17;
public void print() {
System.out.println("This is an outer class");
}
}
class Example17 {
public static void main(String[] args) {
// inner class
Container container = new Container() {
@Override
public void print() {
System.out.println("This is an inner class");
}
};
container.print();
System.out.println( container.c );
}
}
This example shows how an anonymous class can be created in an ad hoc way to override a single method from the original class. This is one of the many possible applications of this type of inner class. The output of this program is:
This is an inner class
17
Process finished with exit code 0
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- PostgreSQL技術內幕:事務處理深度探索
- Java技術手冊(原書第7版)
- 數據結構簡明教程(第2版)微課版
- Python金融數據分析
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優化計算
- Building Minecraft Server Modifications
- Mastering openFrameworks:Creative Coding Demystified
- SQL Server 入門很輕松(微課超值版)
- 現代C:概念剖析和編程實踐
- MyBatis 3源碼深度解析
- R語言數據挖掘:實用項目解析
- 網頁設計與制作
- 從零開始學Unity游戲開發:場景+角色+腳本+交互+體驗+效果+發布
- Java EE輕量級解決方案:S2SH