构造器内部的动态方法行为

JAVA构造函数中如果牵扯到其它被重写的函数可能会引发问题, C++中调用父类构造函数时父类仅仅会去调用自身的函数去完成构造任务, 并不会考虑子类重写(多态)这种情况. JAVA恰恰相反, 如果构造过程会出现子类重写, 而且正在构造的也是子类的对象, 就会去调用子类的重写方法. 这就有可能引发一些奇怪的问题 ,比如牵扯到子类还没有实例化的变量等.
package com.cnsuning.util;
public class Shape {
	public Shape() {
		// TODO Auto-generated constructor stub
		System.out.println("before shape draw");
		draw();
		System.out.println("after shape draw");
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
	public void draw(){
		System.out.println("Shape draw");
	}
}
package com.cnsuning.util;
public class Circle extends Shape{
	public Circle() {
		super();
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
	public void draw(){
		System.out.println("circle draw");
	}
}
package com.cnsuning.src;
import com.cnsuning.util.Circle;
public class Main {
	public Main() {
		// TODO Auto-generated constructor stub
	}
	public static void main(String[] args) {
		Circle c = new Circle();
	}
}
before shape drawcircle drawafter shape draw
所以在java的构造函数中, 尽量不调用其它函数, 或者调用final/private函数, 尽量避免调用可能被继承的函数.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值