JAVA语意上的漏洞

转自: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复杂一点,但符合语义学和工程学。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值