驚奇之一
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,主要是因為:上面的初始化順序並不完整,