get 方法如何知道它需要什么 return

How does get method knows what it needs to return

我不太理解什么时候可以 returned

例如,我将使用 get 和 set 方法:

情况一:

Class:

public class Debb {
         private String word;
         public void setName(String n){
         word = n;
           }

         public String getName(){
             return word;
           }

         public void say(){
             System.out.println(getName());
             }

           }

主要:

 public class nebb {
    public static void main(String args[]){ 
       String plane = "plane";


       Debb temp = new Debb();
       temp.setName(plane);
       temp.say();
  }
 }

案例 2:

Class:

       public class lav {
          private String word;
          public void setName(){
                word = "luka";
              }

          public String getName(){
                return word;
              }

          public void say(){
                System.out.println(getName());
                    }
               }

主要:

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

         lav temp = new lav();
         temp.say();
      }
    }

我完全理解案例 2 的情况。 getName() 与 setName() 没有联系,所以它不知道 return 是什么,我会得到 null。

但是情况 1 呢,getName() 方法如何知道它需要 return 来自 setName() 的单词值。

getName() 返回 word 并且您使用 setName() 将其设置为 "plane"。

I totally understand what happens with case 2 . getName() does'nt have connection with setName() so it does'nt know what to return and i will get null.

实际上你误解了这一点,getName() 再次返回 word 但在这种情况下,由于你没有为它提供任何值,它被初始化为默认值 null

class 有字段 String 字。

private String word;

当你说

public void setName(String n){
    word = n;
}

你说的是

public void setName(String n){
    this.word = n;
}

因此您的 getName 在调用

时正在访问 相同的 字段
public String getName(){
   return this.word;
}

在您的方法中 setter 当您将 word 设置为 "plane" 时。

 public void setName(String n){
     word = n;
       }

当你用getter方法

得到它时,word的值就来了
 public String getName(){
         return word;
       }

因为你指的是同一个变量。在这样的方法中添加键 this 是一种很好的做法。

  public void setName(String n){
     this.word = n;
       }