When do I use.metodo(). metodo()?

Asked

Viewed 152 times

-3

Good night. I have one question: when I use a syntax like: metodo(). metodo()? When and how I use this method?

  • 3

    When you need to do this. I can tell you what it is, when you use it is a little more complicated without a context. But I might just want to know this: https://answall.com/q/106955/101

  • 2

    When the first call returns a non-null object whose only utility you have for it is to call a method belonging to that returned object.

  • 2

    My comment above applies when the returned object is not the initial object itself, when objeto.metodo() != objeto; for cases where objeto.metodo() == objeto, we have something closer to Fluent API, as mentioned by @Maniero

2 answers

2

In a nutshell always when the method returns an object that will allow it to be accessed through the point.

for example:

I have this first class here, the Puppy class, which will have as attributes a name of type String, an age of type int and finally an object of type Owner. This attribute donoDoCachorro will behave like the other attributes, being able to access its properties, also note that the name is also an object, since the String is an Object. After having understood this, we will soon see a constructor that receives an Dono object and a bark method, this method will just print on the screen "Au Au".

public class Cachorro{
   String nome;
   int idade;
   Dono donoDoCachorro;

   public Cachorro(Dono dono){
       this.donoDoCachorro = dono;
   }

   public void latir(){
      System.out.println("Au Au");

   }
}

Remember that in the Puppy class we had an attribute like Dono? Well, that’s his class. It has several attributes, such as name, phone, age all String type, below it has a default constructor and then a display method, which will print on the screen the name and age of the owner.

public class Dono{
   String nome;
   String idade;
   String telefone;
   String endereco;

   public Dono(){

   }

   public void apresentar(){
      System.out.println("Olá, meu nome é " + nome + " tenho " + idade " 
                          anos, tudo bem com você?");
   }
}

Well done and explained the two classes, let’s instance it (create the classes). In the first lines you created a Dono object and prompted it, and then created a puppy object that also prompted only that this time passed as argument an owner. I hope you’ve understood so far.

public class Teste{
   public static void main(String[] args){

      Dono dono = new Dono();
      Cachorro rex = new Cachorro(dono);

      // Agora queremos fazer o cachorro latir, para isso devemos chamar o
      // nome do objeto Cachorro que chamamos de rex, e depois através do 
      // ponto ( . ) acessar os métodos e atributos daquele objeto.

      // veja que acessamos o método latir do cachorro, mas também podemos
      // acessar atributos através do ponto.
      rex.latir();

      // Digamos que queremos sabe a idade do cachorro, basta chama o nome 
      // do objeto, colocar ponto ( . ) e depois colocar o nome do atributo.
      // nesse caso não precisa de parenteses, já que estamos acessando um
      // atributo e não um método.
      rex.idade;

      // Agora queremos acessar o atributo dono do objeto cachorro,
      // lembra-se que esse esse atributo é um objeto? bom prossigamos.
      rex.dono;

      // Bom já acessamos o atributo dono do rex. Mas o atributo dono é 
      // um objeto, isso que dizer que todo vez que estivemos acessando 
      // um atributo que seja um objeto ou um método que retorne um objeto
      // podemos acessar suas propriedades.

      // Por exemplo depois que acessei o atributo dono do rex, quero
      // que o dono se apresente.
      rex.dono.apresentar();

   }
}

We can do this infinitely, and through methods and attributes.

For example like:

objeto.metodo().metodo().metodo();

or so:

objeto.atributo.objeto();

or even so:

objeto.atributo.objeto().atributo.objeto().atributo;

Remember everything that is object or return object you can do this. the scenario is that it will tell you when and how you should use this way, for example in the code we did wanted to access the attribute owner of the object dog. and then access the display method of the owner attribute. There is no rule for this, only practice will tell you this.

2

This is called method chaining (method chaining).

It can be used to give more clarity in the code and to use you need each method to return an instance of the object that has, in turn, the method to be called in the sequence. For example:

class Pessoa {

 private String nome;
 private int idade;
 private String profissao;

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

 public Pessoa setIdade(int idade) {
  this.idade = idade;
  return this;
 }

 public Pessoa setProfissao(String profissao) {
  this.profissao = profissao;
  return this;
 }
}

Each of the methods, after being called, returns an instance of the class itself, and this is what allows us to then string (i.e., call in sequence) the methods we want.

In our code we would use it like this:

Pessoa pessoa = new Pessoa().setIdade(30).setNome("Maria").setProfissao("Programadora");

Browser other questions tagged

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