Java和C++在细节上的差异(三) (三)

2014-11-24 03:03:10 · 作者: · 浏览: 13
public Employee(int jobYears,String name) {
10 _name = name;
11 _jobYears = jobYears;
12 _salary = 0;
13 }
14
15 public void raiseSalary() {
16 //这里也可以不使用this作为内部该内部类对象的外部类对象
17 //引用,可以根据需要替换为其他外部类对象的引用,如:
18 // Employee other = new Employee();
19 // InnerClass innser = other.new InnerClass();
20 InnerClass inner = this.new InnerClass();
21 if (test())
22 _salary += 1000;
23 }
24 ......
25 }
注:在外部类的作用域之外调用public内部类的语法为 OutClass.InnerClass。
3) 局部内部类的可见范围仅仅限于声明该局部类的函数内部,见如下代码:
1 public void start() {
2 class TimePrinter implements ActionListener {
3 public void actionPerformed(ActionEvent e) {
4 Date now = new Date();
5 System.out.println("At the tone,the time is " + now);
6 //beep为外部类的域字段
7 if (beep)
8 Tookkit.getDefaultToolkit().beep();
9 }
10 }
11 ActionListener l = new TimePrinter();
12 new Timer(interval,l).start();
13 }
局部类同样可以访问函数内部的局部变量,但是要求该变量必须是final的。
1 public void start(final bool beep) {
2 class TimePrinter implements ActionListener {
3 public void actionPerformed(ActionEvent e) {
4 Date now = new Date();
5 System.out.println("At the tone,the time is " + now);
6 //beep为外部函数的局部变量。
7 if (beep)
8 Tookkit.getDefaultToolkit().beep();
9 }
10 }
11 ActionListener l = new TimePrinter();
12 new Timer(interval,l).start();
13 }
为了规避局部类只能访问final局部变量的限制,既一次赋值之后不能再被重新赋值。但是我们可以通过数组的方式进行巧妙的规避,在下例中数组counter对象本身是final的,因此他不可以被重新赋值,然而其引用的数组元素则可以被重新赋值,见下例:
1 public void test() {
2 final int[] counter = new int[1];
3 for (int i = 0; i < dates.length; ++i) {
4 dates[i] = new Date() {
5 public int compareTo(Date other) {
6 //这里如果counter不是数组,而是被定义为final int counter,
7 //则会导致编译失败。
8 counter[0]++;
9 return super.compareTo(other);
10 }
11 }
12 }
13 }
C++中同样可以做到这些,其规则和Java的主要差异为C++的内部类无法直接访问外部类的任何成员。
1 class OuterClass {
2 public:
3 void testOuter() {
4 class FunctionInnerClass {
5 public:
6 void test() {
7 printf("This is FunctionInnerClass.\n");
8 }
9 };
10 FunctionInnerClass innerClass;
11 innerClass.test();
12 }
13 };
14
15 int main()
16 {
17 OuterClass outer;
18 outer.testOuter();
19 return 0;
20 }
4) 匿名内部类,其基本规则和局部内部类相似,差别在于该内部类不能有声明构造函数,这主要是因为Java要求类的构造函数和类名相同,而匿名内部类自身没有类名,因此在new新对象的时候,传入的构造函数参数为超类的构造函数参数。C++中不支持匿名类。见下例:
1 public void start(final bool beep) {
2 ActionListener l = new ActionListener() {
3 public void actionPerformed(ActionEvent e) {
4 Date now = new Date();
5 System.out.println("At the tone,the time is " + now);
6 //beep为外部函数的局部变量。
7