c++ 嵌套类
C++中的嵌套类是一种类之间的关系, 不是对象之间的关系
class LinkedList
{
private:
class Link{ // a nested class
public:
Link* next;
int data;
};
public:
class Iterator{
public:
void insert(int x);
void erase();
};
LinkedList() {}
};
LinkedList::Iterator itr; // 可以这样访问类并创建对象
Java内部类
内部类的对象有一个隐式引用,它引用了实例化该内部对象的外围类对象
public class Test {
public static void main(String[] args) {
TalkingClock clock = new TalkingClock(1000, true);
clock.start();
System.out.println(clock); // 输出 "This is an outer class!"
TalkingClock.TimePrinter t = clock.new TimePrinter(); // 从外部建立内部类对象必须通过外部类对象
t.changeDescription("Change");
System.out.println(clock); 输出 "Change"
JOptionPane.showMessageDialog(null, "Quit program?"); // 进入事件等待模式
System.exit(0);
}
}
class TalkingClock {
private int interval;
private boolean beep;
private String description = "This is an outer class!";
public TalkingClock(int interval, boolean beep) {
this.interval = interval;
this.beep = beep;
}
@Override
public String toString() {
return description;
}
public void start() {
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
public class TimePrinter implements ActionListener {
public void changeDescription(String description){
TalkingClock.this.description = description;
}
// 当前内部类对象中,this 依旧本类对象引用.
// TalkingClock.this 为外围内对象引用。
public void actionPerformed(ActionEvent event) {
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep)
Toolkit.getDefaultToolkit().beep();
}
}
}
神奇的匿名内部类
public class Test {
public static void main(String[] args) {
final ArrayList<String> friends = new ArrayList<>();
friends.add("harry potter");
friends.add("Hermione Jean Granger");
friends.add("Ron Weasley");
System.out.println(new ArrayList<String>(){
{
System.out.println(friends.toString());
this.add("yajun yang");
add("JG Zhang");
add("Peng Li");
}
});
}
}
输出:
[harry potter, Hermione Jean Granger, Ron Weasley]
[yajun yang, JG Zhang, Peng Li]