• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java constructor safety. How to tell if I need to move code from constructor to init()?

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What should I be aware of when designing a constructor? Aside from obviously thread specific situations  I am aware of two cases:


(1) A minimal example of an error. This isn't specific to constructor. Fix is straightforward.



(2) This is a better example. Debugging is still reasonably simple.

What else should one be aware of when designing a constructor?



 
Bartender
Posts: 1868
81
Android IntelliJ IDE MySQL Database Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to CodeRanch okli okim.

One thing that you may not be aware of with constructors is constructor chaining with this(). This is where one constructor calls another constructor.
Sample shown below:

There are some other items of note:
  • If you do not explicitly supply any constructors, then a no-arg constructor is created by the compiler for you at compile time.
  • You can access static methods and variables from within a constructor.
  • You cannot access instance methods from within a constructor.
  • You can set instance variables from within a constructor.
  • When you inherit/extend a class you can call the parent constructor using super() when placed inside of a child's constructor as shown below:


  • If you do use super() then it must be the first line of the constructor.

    There is no rule as to when to move away from a constructor and to use something like a builder or factory pattern.
    That said, the long the parameter list the more likely people are going to get it incorrect or the more time people will spend looking back at the definition.
    This holds true for both methods and constructors. I think that most people would be fine with three to five arguments for a method/constructor.
    Depending on the object and it's use.

    However, if you mean the use of initialization block(s) then I would say (from your subject line):
    Even though you can use an initialization block nearly anywhere, please put it near the top of the source file for everyone's sake.
    Be careful, you cannot to access instance variables from static initialization block(s).
     
    Marshal
    Posts: 79180
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Pete Letkeman wrote:Welcome to CodeRanch . . .

    Ditto

    You cannot access instance methods from within a constructor. . . .

    Yes, you can. But you s‍hould only call methods marked final or private from the constructor.

    OP: The reason you were getting a null pointer exception is that you were trying to use an uninitialized field. I wouldn't call that a minimal error, though you are right that its solution is straightforward.
     
    Pete Letkeman
    Bartender
    Posts: 1868
    81
    Android IntelliJ IDE MySQL Database Chrome Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Yes, you can. But you s‍hould only call methods marked final or private from the constructor.


    Sorry, my mistake. Thanks for clearing this up.
    I'm still learning as I go and hope that I won't make that mistake again.
     
    Saloon Keeper
    Posts: 15510
    363
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Also, check out this thread: https://coderanch.com/t/682106/java/constructor#3199923
     
    okli okim
    Greenhorn
    Posts: 3
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I am interested in RTE cases, especially those that cause floating bugs and are common. Compile time exceptions are easy to spot and fix, hence cause less troubles. I should have being more clear in the first post.

    @Pete Letkeman Thank you for response.
    Your code sample compiles and runs as expected.

    Pete Letkeman wrote:If you do use super() then it must be the first line of the constructor.


    This is a good example of a compile time error. would cause a compile time error, highlighted in red and a light bulb will suggest an autofix - moving `super` to first line of the constructor.
     
    okli okim
    Greenhorn
    Posts: 3
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:OP: The reason you were getting a null pointer exception is that you were trying to use an uninitialized field. I wouldn't call that a minimal error, though you are right that its solution is straightforward.


    Just to be clear - I've designed those examples from scratch to show what I mean by constructor related errors.

    Stephan van Hulst wrote:https://coderanch.com/t/682106/java/constructor#3199923
    (1) don't pass 'this' to methods of other classes,
    (2) don't call methods of the current class unless they are private, final or static
    (3) don't start new threads, and
    (4) don't call private, final or static methods that indirectly do any of the previous three points.


    Insightful, thank you. Questions:
    (1) Model view constructor pattern. Service creates an instance of a . Model will never change View or Controller, so those are final. Model has field variables   and . Here comes Catch 22. and  both  also have  I can't do because this is not ready. I don't want to remove keyword because it makes code more brittle. Flags like read only   don't look good. What should one do about it?

    (2) Given that negates keyword, is safe?  
     
    Pete Letkeman
    Bartender
    Posts: 1868
    81
    Android IntelliJ IDE MySQL Database Chrome Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Private and final do not cancel or negate each other.

    Private, public, protected and package default are access modifiers.
    Final, abstract, etc (I'm not going to list them all) are non access modifiers.

    You can have a private method in a class which does not get inhered when you extend the class.
    You can have a final method in a class which does get inhered when you extend the class. You cannot override the method.

    You can have a private variable in a class which does not get inhered when you extend the class.
    You can have final variable in a class which does get inhered when you extend the class. You cannot override the variable.

    Please note that a final variable does not need to be initialized when declared and the following is 'perfectly fine' according to Java:

    However 'perfectly fine' does not mean that you should do it as this could be hard to follow when debugging.
    private final void doSomething(){} is perfectly runable as shown below:

    I'm not too sure of the uses practical uses of both private and final for the same method.
    Most likely this affect inner classes which I have not learned too much about yet.

    okli okim wrote:highlighted in red and a light bulb will suggest an autofix


    This would suggest that you are using an IDE. Which IDE are you using?
    Not that it matters too much, however some people know all of the inns and outs of an IDE and they may be able to help with some optimizations or gotchas.

    Edit: Grammar mistake fixed.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15510
    363
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Okli, the situation you describe is flawed, because a model should NEVER have a reference to a controller or view.

    Knows about
    ModelModel
    ViewModel, View
    ControllerModel, View, Controller
     
    reply
      Bookmark Topic Watch Topic
    • New Topic