Java Can we declare an object variable in the constructor?

When creating an object, can we declare and initialize the object variable in constructor?

I am creating an XML based object. The XML format is derived from the previous system and is dynamic.

Therefore, an object variable is based on elements. it will be better if I declare a variable in the constructor.

In the code below, we can declare temp as an object variable.

For instance:

public class A
{
    public A()
    {
        HashMap<String, Object> temp = new HashMap<String, Object>;
    }
}

I could not find a sample code for this ideology.
Any suggestions?

+4
source share
5 answers

I think you are looking for something a little different.

public class A {
   // Constructor
   private A() {
   }

   public static A createObjectA(...) {
      A result = new A();
      // In here transform the XML in a suitable format and set it into the result object.
      // Return the result
      return result;
   }
}

. , , , .

, A, A :

A newObj = A.createObjectA(...);

, , , , .

Ofc , ( ++).

0

, , , . , .

+1

, .

public class A
{
   HashMap<String, Object> temp;
    public A()
    {
         temp = new HashMap<String, Object>;
    }
}

, , .

+1

, .

.

temp ( { }):

public class A { 

  public A() {
      Map<String, Object> temp = new HashMap<String, Object>;        
  } // end scope of visibility for `temp`

, ( ..).

, .

:

public class A {

  Map<String, Object> temp;

  public A() {
      temp = new HashMap<String, Object>;        
  }
  // you can use it here

BTW
:

Map temp = new HashMap;

:

HashMap temp = new HashMap;

: ArrayList Java

+1

(, ). , , .

, - , .

0

All Articles