Page 1 of 2 12 LastLast
Results 1 to 20 of 25
Like Tree4Likes

Thread: The job of a constructor

  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default The job of a constructor

    To the best of my knowledge, the job of a constructor is
    1. to create space in memory for the object being created
    2. to initialize (i.e. assign values to) the fields of the object


    Now, when we create and use threads by implementing the Runnable interface, we do something like

    Java Code:
    public class HelloRunnable implements Runnable {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }
    
        public static void main(String args[]) {
            (new Thread(new HelloRunnable())).start();
        }
    
    }
    My question is from the statement in the main().

    I understand that start() is an instance method of the Thread class, so we are creating a new Thread object, and using the dot notation with it to start the thread associated with it.

    I also understand that this thread object must be provided with the implementation of the run() method (or the class/object containing implementing the run()) so that it has something to run().

    But why are we passing the object which has the implementation of run() (i.e. the object created by new HelloRunnable() ) to the constructor Thread() responsible for only creating a Thread object? What does the Thread() constructor do with the object having the implementation of run()?

    Thank you in advance.

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    903
    Rep Power
    2

    Default Re: The job of a constructor

    The Thread constructor expects an object that implements runnable. It will call the run() method on it when it starts. The important word here is Runnable. You class implements Runnable and therefore is a candidate as an object for the Thread constructor.

    There are lots of reasons why this is a good practice. For example when you want to adjust some settings on the Runnable object:
    Java Code:
    public class HelloRunnable implements Runnable {
        private String url;
    
        public void setURL(String url) {
            this.url = url;
        }
        
        public void run() {
            //lots of work going on here
        }
    }
    
    
    public class SomeWorker {
    
       public static void main(String[] args) {
          HelloRunnable runner = new HellowRunnable();
          runner.setURL("http://...........");
          runner.setSomeOtherValue(asdasd);
          runner.setTimeout(1000);
          
          new Thread(runner).start();
       } 
    
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: The job of a constructor

    The Thread constructor expects an object that implements runnable. It will call the run() method on it when it starts.
    Firstly, thank you for answering! What I understand here is that you are saying the Thread constructor expects an object that implements runnable(), because this constructor is going to call the run() method of the object passed when it starts.

    But that is not the job of the constructor right? Although we know that the thread we are trying to start by invoking start() does need the implementation of run() so that it has something to run, the constructor is not there to ensure that his class has something to run (that is the code in run() ) right?

    1. The constructors normally assign the values passed to them to the fields of the object they are creating. So what is the Thread constructor assigning the "new HelloRunnable()" to?

    2. Is there a way to see the implementation of the Thread constructor, so that one can see "to what object of Thread is it assigning the HelloRunnable object passed to it."

    Thank you in advance.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default Re: The job of a constructor

    Quote Originally Posted by Zarah View Post
    Firstly, thank you for answering! What I understand here is that you are saying the Thread constructor expects an object that implements runnable(), because this constructor is going to call the run() method of the object passed when it starts.

    But that is not the job of the constructor right? Although we know that the thread we are trying to start by invoking start() does need the implementation of run() so that it has something to run, the constructor is not there to ensure that his class has something to run (that is the code in run() ) right?

    1. The constructors normally assign the values passed to them to the fields of the object they are creating. So what is the Thread constructor assigning the "new HelloRunnable()" to?

    2. Is there a way to see the implementation of the Thread constructor, so that one can see "to what object of Thread is it assigning the HelloRunnable object passed to it."

    Thank you in advance.
    A bit of nitpicking: it's the 'new' operator that allocated memory for the new object; it's the job of the constructor (and the optional initialization block(s)) to set the memory of the new object to sensible values. The constructor of the Thread class sets one of its members to the Runnable passed to the constructor of that class; the start() method uses the Runnable to execute the code in its run() method after you have called the start() method on the thread.

    b.t.w. the Oracle JDK normally comes with a file src.zip that contains all source code of all classes in the public API (see the installation directory of your JDK).

    kind regards,

    Jos
    Zarah likes this.
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: The job of a constructor

    Quote Originally Posted by Zarah View Post
    But that is not the job of the constructor right? Although we know that the thread we are trying to start by invoking start() does need the implementation of run() so that it has something to run, the constructor is not there to ensure that his class has something to run (that is the code in run() ) right?
    No, that is very much the job of the constructor. The most important thing a constructor does is initialize an object's fields so the object is in a valid and consistent state. Every object should be valid and complete when its constructor returns. If anything is missing or invalid, the constructor should throw an exception.
    Get in the habit of using standard Java naming conventions!

  6. #6
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: The job of a constructor

    Quote Originally Posted by JosAH View Post

    b.t.w. the Oracle JDK normally comes with a file src.zip that contains all source code of all classes in the public API (see the installation directory of your JDK).
    I just saw the file Thread in the java.lang package of the src.zip, and it does not seem to contain any constructors. This has left me confused.

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,655
    Rep Power
    5

    Default Re: The job of a constructor

    Quote Originally Posted by Zarah View Post
    I just saw the file Thread in the java.lang package of the src.zip, and it does not seem to contain any constructors. This has left me confused.
    That just proves how much patience you have; there are a great number of constructors in there, they're just a little further down in the source file than you would expect. Try a case-sensitive search for 'Thread(' and see for yourself in mere seconds.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: The job of a constructor

    The most important thing a constructor does is initialize an object's fields so the object is in a valid and consistent state.
    If anything is missing or invalid, the constructor should throw an exception.
    Thank you. It just made me question about the zero-parameter constructors, but then I remembered that the zero parameter constructor just calls upon the constructor of the super class. I hope I am right about that.

    It was actually the member of the Thread to which the passed Runnable is assigned which mainly worried me in this example. The answer from JosAH clarified me about it.

  9. #9
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    903
    Rep Power
    2

    Default Re: The job of a constructor

    Quote Originally Posted by Zarah View Post
    I just saw the file Thread in the java.lang package of the src.zip, and it does not seem to contain any constructors. This has left me confused.
    This one always works for me:Thread (Java Platform SE 7 )
    gimbal2 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,655
    Rep Power
    5

    Default Re: The job of a constructor

    Pssh, posting the API documentation. How predictable. Real programmers look in the source.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: The job of a constructor

    Quote Originally Posted by gimbal2 View Post
    That just proves how much patience you have; there are a great number of constructors in there, they're just a little further down in the source file than you would expect. Try a case-sensitive search for 'Thread(' and see for yourself in mere seconds.
    OK. I could not carry out a search properly in eclipse, and tried to locate it with my own eyes and failed. I just found it and although I do not understand the init(...) kinda code inside it. But I'm no longer much curious about it either. I'll try to be more alert in future.
    gimbal2 likes this.

  12. #12
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: The job of a constructor

    Pssh, posting the API documentation. How predictable. Real programmers look in the source.
    I know this will go off-topic but I often think about it (and your 'patience' comment made me think about it again) and so I am compelled to say this here:

    Although I am nothing near to a programmer, but I don't understand how is looking into huge files for one small semi-colon or variable even possible for programmers, I mean I would never think of trying to learn programming if these API documentations did not exist. TBH, if I don't look at my own code for a month and then get back to it, it irritates me to read it and try to remember what I did and why (and I always just link it to my bad memory); putting aside that extremely difficult source code written by the programmers writing the API's.

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,655
    Rep Power
    5

    Default Re: The job of a constructor

    You also need to work on your sarcasm detection skills, I was just making an obvious joke ;) Of course you look in the API documentation and not in the source.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  14. #14
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: The job of a constructor

    Whatever! :|

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default Re: The job of a constructor

    Quote Originally Posted by gimbal2 View Post
    Pssh, posting the API documentation. How predictable. Real programmers look in the source.
    Sissie; real men (like me) read the compiled .class files.

    kindest regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  16. #16
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,655
    Rep Power
    5

    Default Re: The job of a constructor

    Quote Originally Posted by JosAH View Post
    Sissie; real men (like me) read the compiled .class files.
    Stop wagging that walking stick at people grandpa, you'll poke out someone's eye.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default Re: The job of a constructor

    Quote Originally Posted by gimbal2 View Post
    Stop wagging that walking stick at people grandpa, you'll poke out someone's eye.
    In my days (when everything was better), we had to work for our punched cards in the mine (29 hours per day); well, we called them punched cards but they were pebbles. We were happy then ...

    wippersnappers ...

    kindest regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  18. #18
    Icandoit is offline Member
    Join Date
    Oct 2013
    Posts
    9
    Rep Power
    0

    Default Re: The job of a constructor

    Essentially Thread's constructor takes a Runnable object, your HelloRunnable class implements runnable thusfor is also an instance of Runnable

    Let me create an example

    Java Code:
    public class EffectiveJava {
    	public static void doStuff(Stuffs s) {
    		s.run();
    	}
    	public static void main(String args[]) {
    		EffectiveJava.doStuff(new BigStuff());
    	}
    }
    
    interface Stuffs {
    	public void run();
    }
    
    class BigStuff implements Stuffs {
    	public void run() {
    		System.out.println("BigStuff");
    	}
    }
    
    class SmallStuff implements Stuffs {
    	public void run() {
    		System.out.println("SmallStuff");
    	}
    }
    That will print out "BigStuff" because BigStuff essentially "fills" the method inside Stuffs and whatever's in there is preformed. Same thing would happen if you extended a class and override a method. This has a lot of to with polymorphism, to put the constructor's function into a more clear view here's another example

    Java Code:
    public class EffectiveJava {
    	Stuffs s;
    	public EffectiveJava(Stuffs s) {
    		this.s = s;
    	}
    	public void doStuff() {
    		s.run();
    	}
    	public static void main(String args[]) {
    		new EffectiveJava(new BiggerStuff()).doStuff();
    	}
    }
    
    interface Stuffs {
    	public void run();
    }
    
    class BiggerStuff extends BigStuff {
    	@Override
    	public void run() {
    		System.out.println("BiggerStuff");
    	}
    }
    
    class BigStuff implements Stuffs {
    	public void run() {
    		System.out.println("BigStuff");
    	}
    }
    
    class SmallStuff implements Stuffs {
    	public void run() {
    		System.out.println("SmallStuff");
    	}
    }
    If you didn't pass in an instance of "Stuffs" inside the constructor it would throw a NullPointerException
    Last edited by Icandoit; 03-17-2014 at 01:09 PM.
    Zarah likes this.

  19. #19
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    903
    Rep Power
    2

    Default Re: The job of a constructor

    Quote Originally Posted by Icandoit View Post
    Essentially Thread's constructor takes a Runnable object, your HelloRunnable class implements runnable thusfor is also an instance of Runnable

    Let me create an example

    If you didn't pass in an instance of "Stuffs" inside the constructor it would throw a NullPointerException
    Next time don't bother. Your code has NOTHING to do with Threads nor the Runnable interface. The fact that you have a run() method doesn't make you implement Runnable.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  20. #20
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,655
    Rep Power
    5

    Default Re: The job of a constructor

    Quote Originally Posted by Icandoit View Post
    interface Stuffs {
    public abstract void run();
    }
    Does that even compile? I hope not.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 5
    Last Post: 08-11-2012, 09:50 AM
  2. Java - Constructor Method versus Constructor
    By brocksoffice in forum New To Java
    Replies: 1
    Last Post: 08-01-2012, 09:17 AM
  3. Replies: 5
    Last Post: 12-14-2011, 01:47 PM
  4. Replies: 0
    Last Post: 12-19-2007, 09:10 AM
  5. Replies: 0
    Last Post: 12-19-2007, 09:01 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •