Can I write the return method independently in main?

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

When calling a method that returns a specific value or a specific object in the main function,

Don't you usually substitute that method for a variable or object of that type?

I wonder how you can use it independently.

가령 다음과 같은 코드가 있다고 합시다.

package java Study;

public class Pet {
    private String name;
    private String eyeColor;
    private int hungryLevel;

    public Pet setName(String name) {
        this.name = name;
        return this;
    }

    public Pet setEyeColor(String eyeColor) {
        this.eyeColor = eyeColor;
        return this;
    }

    public static void main(String[] args) {
        Pet p1 = new Pet();
        p1.setName("Kitty");
        System.out.println(p1.setName("Kitty"));
    }
}

Doesn't return mean that the entered value is returned after obtaining the result value through a specific operation?

Doesn't setName return this, or p1 itself, in the above code?

Until now, we have used the method to use the object

I've been using that address as an acceptable variable.

Of course, I thought there should be a variable that accepts the return value of the method

If you call setName as shown above, without sync error and runtime error

I don't understand what's going on.

I want to know how return works in Java.

java method

2022-09-20 14:59

2 Answers

I don't know about Java, but I'll answer it.


2022-09-20 14:59

Why do you not need a variable to accept the return value

Seol#1) methods are stacked and executed from the main function one by one The theory that even if the method is executed and there is a return value, it cannot be allocated as a variable and just passes by.

Seol#2) Even if the return value is given, if the person who wrote it does not put it or does not use it, it will be treated as a garbage value. If you give it back 3, the constant of 3 if you don't use it is just trash. The method gives a value, but if you don't use a variable, the computer won't write memory. Or empty the memory of the object returned by the garbage collection.

method chaining

String str2 = new StringBuffer().append("hello").append(" ").append("world").toString();

Section#1) By continuously returning this to the string reference variable str2, successive methods can be invoked on the same object


2022-09-20 14:59

If you have any answers or tips


© 2022 pinfo. All rights reserved.