Define method within the body of another method in Java

Asked

Viewed 638 times

0

Hello, I was researching on Java and I came across the following code:

cliente.getInetAddress().getHostAddress()

I didn’t understand it very well. Is this a method within another method? I tried to do:

public class Post {
    public void Post(){
        public void test(){}
    }
}

But Netbeans says the code is wrong. Well, I’d like to know how it works (if you could implement a simple example code)

Code link I found

1 answer

6


On the line

cliente.getInetAddress().getHostAddress()

First the client variable has this method getInetAdress(), he another object which in turn has another method getHostAdress()

The technical term is chaining - chained call

An example would be:

public class Pessoa{

    private Date dataNascimento = new Date();

    public Date getDataNascimento(){
        return dataNascimento;
    }
}



public class Main{
   public static void main(String... args){
   Pessoa p =new Pessoa();
   System.out.println(p.getDataNascimento().toString())
   }

}

So in the code above I call a method toString() from the Object Date returned from the Person class. The method toString() is defined in the Date class, not in the person class:

https://docs.oracle.com/javase/7/docs/api/java/util/Date.html

Browser other questions tagged

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