2

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();

4 Answers 4

3

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();
  }
}
1

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.

1

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(){

   }
}
1

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(..)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.