• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best way of intialization

 
tushar jayawant
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi to all


Which is best way of intialization the Instance Variable

1) class A {
B b= new B();
C c = new C();

}


2)

class A {
B b ;
C c ;

A(){

b= new B();
c = new C();



}

}


Thankx in Advance
Tushar
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you initialize member variables in the body of the class, the compiler actually puts a copy of that initialization code at the beginning of each constructor, so in terms of efficiency or anything like that, they're really equivalent. The only thing that matters, then, is maintainability and readability.

The rule I follow, loosely, is that primitive types can be initialized to constants in the class body, while objects are created in a constructor. The main reason for this is consistency; some objects have to be created in a constructor (or in an initializer block) because their constructors throw exceptions -- so to be consistent, I do them all that way.

Other people may have other rules.
 
tushar jayawant
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Thankx for the Reply......

Tushar
 
Frank Harper
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The advantage of initializing member variables in the body of the class is that you only have to do it once, instead of for each constructor.

This eliminates potential bugs where someone forgets to initialize a member in in a certain constructor.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic