Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating object in a constructor

Tags:

java

It seems that the result of the following code is the same, so when should I use each?

public class Person {
   public Person() {
       this.family = new Family();
   }
   Family family;
}

to

public class Person {
   Family family = new Family();
}

(one scenario I can think of, is when having multiple constructors and we want to create an instance of family only inside one of them... is that the only case?)

like image 605
Ohad Avatar asked Feb 14 '12 19:02

Ohad


People also ask

Does a constructor instantiate an object?

Constructor is just used to initialize the state of the object created. It does not create an object itself. An object state can also be contained in an abstract super class. So, the purpose of invocation of Abstract class constructor, is only to initialize the object completely, and no object is created in process.

How do you initialize an object in a constructor?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

Can we initialize object in constructor Java?

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

Can we create object in constructor?

If we know the name of the class & if it has a public default constructor we can create an object Class. forName. We can use it to create the Object of a Class.


1 Answers

For class variables [static variable] you cannot use the first, since you want the initializtion to happen only once, and not with every time you invoke your constructor.

For instance variables, the second is just a syntatic sugar of the first.
Sometimes you might have to use the second - for argument constructor, which are themselves - passed to your constructor.

like image 164
amit Avatar answered Oct 26 '22 22:10

amit