Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding run() method in Thread subclass

I am just wondering what the result would be if I subclassed a class which extends Thread and I wrote following code and tested:

class A extends Thread {
    public A() {
        this.start();
    }
    public void run() {
        System.out.println(" in A " + Thread.currentThread().getName());
    }
}

class B extends A {
    public void run() {
        System.out.println(" in B " + Thread.currentThread().getName());
    }
}

public class OverrideRun {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
    }    
}

And the result is:

in A Thread-0
in B Thread-1

But I don't understand why two threads are created?

like image 725
java Avatar asked Nov 29 '25 04:11

java


1 Answers

This is because the B b = new B(); statement calls no argument parameter of class B and that calls no argument parameter constructor(Default) of class A.

This is due to constructor chaining.

like image 131
Pramod Kumar Avatar answered Dec 01 '25 19:12

Pramod Kumar