wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes How to use this() in overloaded subclass constructors ( and why) ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to use this() in overloaded subclass constructors ( and why) ?" Watch "How to use this() in overloaded subclass constructors ( and why) ?" New topic
Author

How to use this() in overloaded subclass constructors ( and why) ?

james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
I wrote the following to demonstrate to myself how super works and that is OK unless someone tells me otherwise. I have now run into the sand on use of this() to invoke overloaded constructors. The book I am reading says I can't use both super and this but it doesn't explain how to use this. I know I don't need it here because the constructors don't do much but I would still like to understnad how to do it. Grateful for a steer.

/*
C:\Documents and Settings\jd>java tryFormat
65 three
60 three
60 six
100
*/
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
Don't know. Your code is hard to read without the code tags. But I know where you can find an example, the Clock classes in the Deitel Java How to Program book. I can more-or-less remember what it looks like, but I have made some changesNote
  • 1 I have gone from few arguments to many arguments.
  • 2 You can go the other direction.
  • 3 Concentrate as much of your code as possible in one of the constructors.
  • 4 Methods called from the constructor are tagged final (or private)
  • 5 The validation of the values entered is all done in one place, the set methods
  • NB: There was a rather similar subject about 2 weeks ago: look here, particularly noting Sam Mercs' comments.

    Your book is correct that you can't use this() and super() together. If you use either, they must be the first statement in the constructor, and you can't have two "first" statements.
    james dunster
    Greenhorn

    Joined: May 03, 2009
    Posts: 20
    OK, got it thanks. Puzzled by line 57 though.

    This works. I guess same can be done with subclasses if I had something more for the constructors to do.


    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    james dunster wrote:OK, got it thanks. Puzzled by line 57 though.
    Try this version

    public Clock(int hours, int minutes, int seconds)

    That might work better

    And sorry for that mistake.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: How to use this() in overloaded subclass constructors ( and why) ?