Search code examples
javainterfacejava-threads

Trying to simulate Thread behavior in orher class with Java


I have this class:

public class MyThread {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            public void run() {
                System.out.print("Test from Anonymous Class!");
            }
        };
        Thread newThread = new Thread(thread);
        newThread.run();
    }
}

When i run this program, i get Test from Anonymous Class!.

Now, i'm trying to simulate this behavior with another class like this:

interface MyInterface {
    public void doTest();
}

class MyClass implements MyInterface {
    public MyClass() {}

    public MyClass(MyInterface myInterface) {}

    public void doTest() {
        System.out.println("Test from MyClass!");
    }
}

public class Test {
    public static void main(String[] args) {
        MyClass myClass1 = new MyClass() {
            public void doTest() {
                System.out.println("Test from Anonymous Class!");
            }
        };

        MyClass myClass2 = new MyClass(myClass1);
        myClass2.doTest();
    }
}

When i run this program, i get Test from MyClass!. Why is in the fist example printing out Test from Anonymous Class!? How can i get the same behavior with MyClass class?

Thanks in advance!


Solution

  • It seems you want to implement a delegation from a class that takes as parameter of the constructor an interface.

    The Thread constructor uses the Runnable instance provided as parameter as target of the execution when you invoke Thread#start() while your custom class doesn't mimic this behavior. You indeed do nothing with the MyInterface parameter passed :

    public MyClass(MyInterface myInterface) {}
    

    To implement a delegation, you should add a MyInterface field in MyClass and value it in the constructor.
    Then use it in doTest() method.

    public MyClass(MyInterface myInterface) {}
    
      private MyInterface myInterface;
      ...
      public MyClass(MyInterface myInterface) {
        this.myInterface = myInterface;
      }
    
       public void doTest() {
           // do some processing
             ..
           // then delegate
          myInterface.doTest();
       }
    }