Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, pass main class to child class, bad coding style?

Please bear with me on this as I'm still getting the hang on Java.

The example bellow reads from a Class named Parent that creates an instance of itself on the main method. It then makes that instance do all sorts of calculations.

Next it fires up a thread named Child passing the Parent instance as a reference to Child.

The Child just sits there monitoring things and, sometimes, fires up public methods on Parent.

It works. The question is, is this poor style? Is there a more Java thinking way of doing this sort of work?

public class Parent {

    // main function that fires up the program
    public static void main() {

        // creates an instance of himself
        // and fires go that does all sorts of fuzzy calculus
        Parent parent = new Parent();
        parent.go();

        // creates a new thread of child and starts it
        Child child = new Child(parent);
        child.start();
    }

    private void go() {
        // all sort of initializations
    }

    public void getDataFromChild(int data) {
        // will get data from running child thread
    }
}



public class Child extends Thread {
    private Parent parent;

    // child constructor grabs Parent instance into "o"
    public Child(Parent o) {
        parent = o;
    }

    // this class main loop
    public void run() {
        while(1==1) {
            doSomething();
            try {
                sleep(1000);
            }
            catch(Exception e) { }
        }
    }

    private void doSomething() {
        parent.getDataFromChild(1);
    }

}

Thank you.

like image 950
Frankie Avatar asked Jan 26 '26 05:01

Frankie


1 Answers

Subclassing Thread is considered bad style. It's better to implement Runnable, and then hand the runnable off to a thread (hmmm... quite analogous to your Parent/Child hand-off!).

Runnable r = new Child(parent);
new Thread(r).start();

Otherwise your Child.java code looks fine to me.

To implement Runnable you just need to provide a run() method:

public class Child implements Runnable {
  private Parent parent;

  public Child(Parent parent) { this.parent = parent; }

  public void run() {
    // what the thread does goes in here...
  }
like image 99
Julius Musseau Avatar answered Jan 27 '26 17:01

Julius Musseau