Ahmed Nabil
Ahmed Nabil

Reputation: 19026

How to initialize all sub NON-Primitive fields of a complex java object when initialize it?

My data model

Class A
    fieldA1 : primitive dataType  
    fieldA2 : primitive dataType 
    fieldA3 : NON-primitive dataType (Class B)
            fieldB1 : primitive dataType  
            fieldB2 : primitive dataType 
            fieldB3 : NON-primitive dataType (Class C)
                    fieldC1 : primitive dataType  
                    fieldC2 : primitive dataType 
                    fieldC3 : NON-primitive dataType (Class D)
                            fieldD1 : primitive dataType  
                            fieldD2 : primitive dataType 

My complex object is (Class A)

My problem is that
When i try to initialize my complex java object
All sub NON-Primitive fields in the first level will be null
For example

A a = new A();

a.fieldA3 -> null
a.fieldA3.fieldB3 -> cant access it (parent is null object)
a.fieldA3.fieldB3.fieldC3 -> cant access it (parent is null object)

Any way/patten to make me able
When initialize a complex java object All sub NON-Primitive fields will be initialize also ?

For example

A a = new A();

a.fieldA3 -> new B(); 
a.fieldA3.fieldB3 -> new C(); 
a.fieldA3.fieldB3.fieldC3 -> new D();

Upvotes: 2

Views: 238

Answers (4)

Saurabh
Saurabh

Reputation: 7964

Initialize the member variables with instance of the class wherever you are declare the variable. So

class A{
private B other;
} 

becomes

class A{
private B other = new B(..)
}

Upvotes: 1

Mubin
Mubin

Reputation: 4239

Why not something simple like this?

public class A {
  B fieldA3;
  public A() {
   fieldA3 = new B();
  }
}

public class B {
  C fieldB3;
  public B() {
   fieldB3 = new C();
  }
}

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Assign an instance of the appropriate type to the field in the constructor.

public class A{

   private B fieldA3;

   public A(){
      this.fieldA3 = new B();
   }
}

Or just assign them in the declaration. Making sure that B,C,D instantiate their fields in their constructors.

public class A{

   private B fieldA3 = new B();

   public A(){

   }
}

Upvotes: 1

Renjith
Renjith

Reputation: 3274

You have to write a constructor in class A and explicitly create all the objects for non-primitive fields.For initialization, you have to go via constructor only.

Upvotes: 1

Related Questions