java在抽象基类构造函数调用该抽象方法,是否可以从Java中的构造函数调用抽象方法?...

Let's suppose I have an abstract Base class that implements Runnable interface.

public abstract class Base implements Runnable {

protected int param;

public Base(final int param) {

System.out.println("Base constructor");

this.param = param;

// I'm using this param here

new Thread(this).start();

System.out.println("Derivative thread created with param " + param);

}

@Override

abstract public void run();

}

And here is one of a few derivative classes.

public class Derivative extends Base {

public Derivative(final int param) {

super(param);

}

@Override

public void run() {

System.out.println("Derivative is running with param " + param);

}

public static void main(String[] args) {

Derivative thread = new Derivative(1);

}

}

The point is that I want my Base class do some general stuff instead of copying it every time.

Actually, it's running fine, the output is always the same:

Base constructor

Derivative thread created with param 1

Derivative is running with param 1

But is it safe IN JAVA to start a thread calling the abstract method in constructor? Because, in C++ and C# it is unsafe in most cases, so far as I know.

Thank you!

解决方案

This code demonstrates why you should never call an abstract method, or any other overridable method, from a constructor:

abstract class Super {

Super() {

doSubStuff();

}

abstract void doSubStuff();

}

class Sub extends Super {

String s = "Hello world";

void doSubStuff() {

System.out.println(s);

}

}

public static void main(String[] args) {

new Sub();

}

When run, this prints null. This means the only "safe" methods to have in a constructor are private and/or final ones.

On the other hand, your code doesn't actually call an abstract method from a constructor. Instead, you pass an uninitialized object to another thread for processing, which is worse, since the thread you're starting may be given priority and execute before your Base finishes its initialization.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值