转自:http://community.csdn.net/Expert/topic/4958/4958971.xml?temp=5.456179E-02
对于长期使用C++的人来说,这样的语义确实叫人一下子难以接受。
/* * Main.java * * Created on 2006年8月17日, 下午8:28 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */
package javaapplication2;
/** * * @author Zenny Chen */
class Parent{ protected int t; public Parent() { System.out.println("Creating Parent..."); create(); } public void create() { System.out.println("Parent created!"); t = 1; }}
class Child extends Parent{ private int c; public void create() { c = 1; System.out.println("Child created!"); } public Child() { System.out.println("Creating Child..."); create(); } public int getValue() { return c + t; }}
public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Child ch = new Child(); System.out.println("The result is: "+ch.getValue()); }}
从语义学和工程学角度,在Child对象被创建时首先要创建其父类域,然后可以根据父类属性来获得创建自身资源的需要。然而Java在处理方法重写这个语义时,执行的是“一刀切”,父类域尚未被创建完就开始调用其子类所重写的方法来。这样很可能造成子类的资源也无法被初始化(若子类构造方法不去构建)。从这点上,C++做得就比较好。创建一个对象就像造房子,一层一层建造。C++中虚函数的多态性不会表现在构造函数和析构函数中,而且构造函数和析构函数也不会受到const对象的限制。尽管在语义的实现上确实要比Java复杂一点,但符合语义学和工程学。