最近看《Thinking in Java》,关于内部类的继承那一章。
其中有一个练习:
“创建一个包含内部类的类,此内部类有一个非默认的构造器(需要参数的构造器)。创建另一个包含内部类的类,此内部类继承自第一个内部类。”
下面是书中给出的代码:
class FirstOuter {
public class FirstInner {
FirstInner(String s) {
System.out.println("FirstOuter.FirstInner() " + s );
}
}
}
public class SecondOuter {
public class SecondInner extends FirstOuter.FirstInner {
SecondInner(FirstOuter x) {
x.super("hello");
System.out.println("SecondOuter.SecondInner()");
}
}
public static void main(String[] args) {
FirstOuter fo = new FirstOuter();
SecondOuter so = new SecondOuter();
SecondInner si = so.new SecondInner(fo);
}
}
我的疑惑是这里,x.super("hello");
,为什么是调用另一个外部类的super(),而且传入的是所继承的内部类的构造器所需要的参数,我搜索了一下没有找到相关的解释,这是固定的语法么
忘各位解惑,谢谢。
迷茫2017-04-17 17:39:20
If you change the code to:
public class SecondOuter {
public static class SecondInner extends FirstOuter.FirstInner {
SecondInner() {
super("hello");
System.out.println("SecondOuter.SecondInner()");
}
}
public static void main(String[] args) {
FirstOuter fo = new FirstOuter();
SecondOuter so = new SecondOuter();
SecondOuter.SecondInner si = new SecondInner();
}
}
class FirstOuter {
public static class FirstInner {
FirstInner(String s) {
System.out.println("FirstOuter.FirstInner() " + s);
}
}
}
x.new is no longer needed. In fact, the simple understanding is that the static inner class is like an object parameter. We must first instantiate the object before further processing the parameters.
黄舟2017-04-17 17:39:20
x.super("hello"); , why is it calling super() of another external class
This is not a call to an external class super
,而是你调用FirstInner
的super
必须这么写。
内部类(非静态)获取时必须有其外部类的对象,这就出现了诸如so.new SecondInner(fo)
x.super("hello")
看似奇葩的语法,理解时你可以忽略掉前端的so.
x.
, it can be understood as a grammatical regulation.
Just like @好学利行 reform, that one may be easier to understand and more common.
PHPz2017-04-17 17:39:20
Is it possible to combine x. new and super(...) into one? It’s the first time I’ve seen this kind of writing.