Why give new in the class attribute?

2

I'm moving from C ++ to JAVA and would like to know why to give new already in the class attribute?

public class ExemploPES2
{
    class y{

        int value;

    }


    class x{

        private y nova = new y();


    }

I do not understand why I give new attribute already. Is it useful to call which constructor?

    
asked by anonymous 06.07.2017 / 13:50

3 answers

2
  

I do not understand why I give new already in the attribute.

You are not required to "give new " in the attribute declaration.

The galley does this to avoid that there is an instance with a null attribute. For example:

public class Y {

    public void fazAlgumaCoisa() {
        //implementação
    }
}

public class X {

    private Y nova;

    public Y getNova() {
        return nova;
    }
}

public class Z {

    public void chamaMetodoDeY() {

        X meuX = new X();
        Y novaDeX = meuX.getNova();

        novaDeX.fazAlgumaCoisa(); //Uma NullPointerException é lançada nessa linha
    }
}

The "default value" for instance variables / non-primitive type attributes is null .

Practices to avoid this scenario

To avoid scenarios like these, solutions like:

Practice # 1 : Instantiate / initialize the attributes in the statement itself (your example);

Practice # 2 : Get an instance (or value) by the constructor of your class:

public class Y {

    public void fazAlgumaCoisa() {
        //implementação
    }
}

public class X {

    private Y nova;

    public X(Y nova) {
        this.nova = nova;
    }

    public Y getNova() {
        return nova;
    }
}

public class Z {

    public void chamaMetodoDeY() {

        X meuX = new X();
        Y novaDeX = meuX.getNova();

        novaDeX.fazAlgumaCoisa(); //Nenhuma Exception será lançada nessa linha 
        //pois você receberá uma instância de Y pelo construtor
    }
}

Practice # 3 : Dependency Injection:

This is already a slightly more advanced topic.

Dependency Injection essentially means that something or someone is going to "inject" a dependency (instance) into their attributes in an automagic way.

Usually we have a Dependency Injection Container that is responsible for injecting them.

A famous example is using the framework Spring :

public class Y {

    public void fazAlgumaCoisa() {
        //implementação
    }
}

public class X {

    @Autowired //Anotação do Spring que injeta uma instância de Y quando for necessário
    private Y nova;

    public Y getNova() {
        return nova;
    }
}

public class Z {

    public void chamaMetodoDeY() {

        X meuX = new X();
        Y novaDeX = meuX.getNova();

        novaDeX.fazAlgumaCoisa(); //Nenhuma Exception será lançada nessa linha 
        //pois o Spring injetará a instância necessária quando for necessário
    }
}

Note: For this to work a few (a handful) of previous settings are needed.

  

Is it to call which constructor? (% with%)

The private Y nova = new Y(); constructor is called.

    
06.07.2017 / 19:42
7

The main reason for using it is the same as C ++, indicating that an heap allocation must be made to support that object, so the variable there will be given a pointer to the allocated object, as in C ++.

Of course in Java you do not have the pointer exposed directly and you can not choose to use new u no, if it is a class, it will always be a type by reference. You can also customize the new operator for this class.

In primitive types this is not necessary because the allocation is done within the class itself, or stack , the value is placed right there and does not need an additional allocation.

In theory it would be possible not to have this operator since every class needs it. But it is still extra information to indicate that it is calling a constructor and not any method that returns an object, giving more readability about the intent of the code. Unfortunately for most Java programmers it ended up becoming only redundant because few observe about the allocation and lifetime of the object, unlike what occurs in C ++.

In your example the variable y is being declared as type y (bad name, should be uppercase, better still if it was a meaningful name), and is calling its constructor to initialize it. p>

In thesis it is possible to not call anything and not initialize, so the variable y would have the value null , but in this example it would not serve much, or any example does not fit. If I did not initialize the field ( I do not like the term attribute for this ) I would have to create a constructor that does this or work with a potentially invalid member until it is somehow initialized.

The Java compiler creates a default constructor whenever you do not provide a constructor. This builder is for call standardization only.

In Java you can only construct an object in this way, it has no alternative syntax like C ++ has.

    
06.07.2017 / 14:06
1

The use of new implies in creating an instance for the right class of the reserved word new , about which constructor is being called in this case is the following in java, when you do not declare any constructor the compiler of Java adds a default constructor, which has no argument, in the example you posted the constructor used is the default.

Note: If a constructor is declared in the class, the default constructor is no longer included by the compiler, and if you want to use it, you will have to manually include it in the class, as in the following code:

class Pessoa {
  String nome;

  public Pessoa() {}

  public Pessoa(String nome) {
    this.nome = nome;
  }
}
    
06.07.2017 / 14:12