惊奇之一
import com.bruceeckel.simpletest.*;
public class Equivalence {
static Test monitor = new Test();
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1 == n2);
System.out.println(n1 != n2);
monitor.expect(new String[] {
"false",
"true"
});
}
}
我一开始以为输出的结果错了,后来看了书才晓得:尽管对象的内容是相同的,但是对象的引用是不同的,而==和!=比较的都是对象的引用,所以才会出现上述的输出结果。如果要比较两个对象的实际内容需要使用特殊的方法equals。n1.euqals(n2)
惊奇之二
//: c06:FinalOverridingIllusion.java
// It only looks like you can override
// a private or private final method.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;
class WithFinals {
// Identical to "private" alone:
private final void f() {
System.out.println("WithFinals.f()");
}
// Also automatically "final":
private void g() {
System.out.println("WithFinals.g()");
}
}
class OverridingPrivate extends WithFinals {
private final void f() {
System.out.println("OverridingPrivate.f()");
}
private void g() {
System.out.println("OverridingPrivate.g()");
}
}
class OverridingPrivate2 extends OverridingPrivate {
public final void f() {
System.out.println("OverridingPrivate2.f()");
}
public void g() {
System.out.println("OverridingPrivate2.g()");
}
}
public class FinalOverridingIllusion {
private static Test monitor = new Test();
public static void main(String[] args) {
OverridingPrivate2 op2 = new OverridingPrivate2();
op2.f();
op2.g();
// You can upcast:
OverridingPrivate op = op2;
// But you can't call the methods:
//! op.f();
//! op.g();
// Same here:
WithFinals wf = op2;
//! wf.f();
//! wf.g();
monitor.expect(new String[] {
"OverridingPrivate2.f()",
"OverridingPrivate2.g()"
});
}
} ///:~
在OverridingPrivate2方法中此时并不是覆盖方法,而是生成了一个新的方法。由于private方法无法触及而且能够隐藏。所以在OverridingPrivate2中定义f、g时并不知道其他f、g的存在,所以这时候是生成一个新的方法。
惊奇之三
//: c07:PolyConstructors.java
// Constructors and polymorphism
// don't produce what you might expect.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;
abstract class Glyph {
abstract void draw();
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println(
"RoundGlyph.RoundGlyph(), radius = " + radius);
}
void draw() {
System.out.println(
"RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
private static Test monitor = new Test();
public static void main(String[] args) {
new RoundGlyph(5);
monitor.expect(new String[] {
"Glyph() before draw()",
"RoundGlyph.draw(), radius = 0",
"Glyph() after draw()",
"RoundGlyph.RoundGlyph(), radius = 5"
});
}
} ///:~
java中复杂对象调用构造器要遵照以下顺序:
radius的初始值是0而不是1,主要是因为:上面的初始化顺序并不完整,