Why give new in class attribute?

Asked

Viewed 321 times

2

I am leaving C++ for JAVA and would like to know why to give new already in class attribute?

public class ExemploPES2
{
    class y{

        int value;

    }


    class x{

        private y nova = new y();


    }

I do not understand why I give new already in the attribute. Serves to call which constructor?

  • 1

    And why wouldn’t it? It’s equal C++. You really wanted to put one class inside the other?

  • 1

    What it is doing seems to be composition, when an object is composed of another object. In this case, the internal object is created within the external. What would be the equivalent code in C++?

  • By the way, why define classes within a class?

  • In Java, you only have references to objects, so you need to give a new

3 answers

7

The main reason to use it is equal to that of C++, indicate that an allocation in heap must be performed to support that object, then the variable present there will receive a pointer to the allocated object, as in C++.

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

In primitive types this is not necessary because 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 him. But it is still an extra piece of information to indicate that it is calling a constructor and not just any method that returns an object, giving more readability about the intent of the code. Unfortunately for most Java programmers it has become only redundant because few observe about the object’s allocation and lifespan, unlike what happens in C++.

In your example the variable y is being declared as y (bad name, should be capitalized, even better if it was a significant name), and is calling your builder to initialize it.

In theory it is possible to call nothing and not initialize, thus the variable y would have the value null, but in this example would not serve much, or every example does not serve. If not initialize the field (I don’t like the term attribute for this) 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 standard builder whenever you do not provide a constructor. This constructor serves only for call building standardization.

In Java you can only build an object this way, it has no alternative syntax as C++ has.

2


I don’t understand why I give new already in the attribute.

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

People do this to prevent 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/attributes of primitive types is null.


Practices to avoid this scenario

To avoid scenarios like these, solutions such as:

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

Practice #2: Receive an instance (or value) by the constructor of its 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.

Injection of Dependencies basically means that something or someone will "inject" a dependency (instance) into its shape attributes self-driving.

Usually we have a Dependency Injection Container who 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 are necessary some (a handful) of previous settings.


Serves to call which builder? (private Y nova = new Y();)

The builder of Y is called.

  • 1

    You answered the question... I had not understood why to give new in the class attribute itself, now I understood that it serves to not declare null attribute.

1

The use of new implies the creation of an instance for the class to the right 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 Java compiler adds a default constructor, which has no argument, in the example you posted the constructor used is the default.

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

class Pessoa {
  String nome;

  public Pessoa() {}

  public Pessoa(String nome) {
    this.nome = nome;
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.