Search code examples
javareturnvoidreturn-type

Dummy variable to handle return of a void method in Java?


When I need to run an expression (an external method for example) outside a method in current object I declare a field variable for that object class and assign return value of that expression to that variable. Like below,

class{
variabletype a=expression();
  public int method(){
  -----}
}

Here expression() is evaluated before start of any methods of the class. It works perfectly unless return type of expression() is void. What I am looking for is a way to achieve the same even when expression() doesn't return anything. More specifically I need a type of dummy variable to do the same thing as done in line 2 of the code shown above even when expression() returns nothing. Note: I have no access to the constructor of the class.


Solution

  • You can use an instance initializer block:

    class YourClass
    {
    
        {
            expression ();
        }
    
        ...
    }
    

    This will execute expression() right before the body of each constructor of your class. It doesn't matter whether expression() returns something, or has a void return type.

    You don't have to introduce any dummy instance variables.

    BTW, your Here expression() is evaluated before start of any methods (except constructor) of the class. assumption is not accurate. Instance variables are initialized before the constructor body is executed (but after the super-class constructor). Therefore expression() is executed before the body of your class's constructor.