0

Here is an example I read today:

class HDFC implements Bank{  
     private final String BNAME;  
     public HDFC(){  
            BNAME="HDFC BANK";  
    }  
    public String getBankName() {  
              return BNAME;  
    }  

}

if it is me, I probably would create like this:

class HDFC implements Bank{  
     private final String BNAME="HDFC BANK";  

    public String getBankName() {  
              return BNAME;  
    }  

}

What's the difference between these two implementations? which one is more appropriate?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Feixiong Liu
  • 443
  • 1
  • 7
  • 14
  • It's going to assign the value to the static with every constructor. It will be null until the constructor is called. Why would anyone ever use the first one? – Ruan Mendes Jun 24 '20 at 20:47
  • If you assign the field directly that assignment happens before the constructor. If you have multiple constructors you'll have to call the setting constructor, or set the value every single constructor. If the value is always going to be a string literal, you might as well make it static too. – nylanderDev Jun 24 '20 at 20:48

1 Answers1

2

The two snippets would behave the same way. You could say that initializing the field directly is a form of syntactic sugar. It becomes convenient if you have multiple constructors and don't want to repeat the same initialization in all of them.

Mureinik
  • 297,002
  • 52
  • 306
  • 350