2015-10-21 19 views
-2

e.x.  如何在不同的功能中使用setter和getter?

 class setterGetter{ 
      String h="null" ; 
      setter(); 
      getter(); 
     } 

     class UseSetterGetter{ 
      setterGetter sg = new setterGetter(); 

      public void A{ 
      sg.setter("abc"); 
      } 

      public void B{ 
      sg.getter(); 
      } 
     } 

的问题是,当我想用​​在函数B吸气,它显示“空”,而不是“ABC”。

有无论如何解决这个问题吗?

+0

我甚至不能遵循这个代码什么? 'setter(String x)'和'getter()'方法在哪里 – 3kings

+0

它们不仅仅是setter和getter。他们也有一些标准格式来实现他们的功能。所以请完成你的代码然后重新检查 – SacJn

回答

0

它将显示为空,因为在此之前您没有调用方法A.它应该是这样的。

class setterGetter{ 
    String h="null" ; 
    public void setter(String h) { 
     this.h = h; 
    } 
    public String getter() { 
     return h; 
    } 
} 

class UseSetterGetter{ 
    setterGetter sg = new setterGetter(); 

    public void A(){ 
    sg.setter("abc"); 
    } 

    public void B(){ 
     A(); 
    sg.getter(); 
    } 
} 
0

您似乎对此代码有很多问题。继续努力吧。这是我认为你的目标?这是一个带有getter和setter的类的示例,以及另一个正在使用它的类。

public class GetterSetter { 

    private String aField; 

    public String getaField() { 
     return aField; 
    } 

    public void setaField(String aField) { 
     this.aField = aField; 
    } 

} 

public class UseGetterSetter { 

    public static void main(String[] args) { 
     GetterSetter a = new GetterSetter(); 

     a.setaField("I am setting the field to be equal to this"); 

     System.out.println(a.getaField() + " printed"); 
     // The result of this code is that the system will print: 
     // "I am setting the field to be equal to this printed" 
    } 

}