java super()的使用注意

class TestThread extends Thread{
	private int sleepTime;
	public TestThread(String name) {
		super(name); //此处有super语句
		sleepTime = (int ) (Math.random() * 6000);
	}
	public void run() {
		try {
			System.out.println(getName() + "going to sleep for" + sleepTime);
			Thread.sleep(sleepTime);
		}
		catch(InterruptedException exception) {;}
		System.out.println(getName() + "Finished");
	}
}
public class HelloWorld  extends Thread{
		
		public static void main(String args[])
		{
			TestThread thread1 = new TestThread("thread1");
			TestThread thread2 = new TestThread("thread2");
			TestThread thread3 = new TestThread("thread3");
			System.out.println("starting threads");
			thread1.start();
			thread2.start();
			thread3.start();
		}
    }

执行结果

thread1-3字符能够正常显示

注释掉super(name);的话 不能正常显示

super(参数):调用基类中的某一个构造函数(应该为构造函数中的第一条语句)

调用super()必须写在子类构造方法的第一行,否则编译不通过。每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值