我有一个与 getter 和 setter 概念相关的小程序,由于我不明白的原因,我得到了 null 值。这是我的代码,我需要在单个对象中传递多个字符串:
public class simple {
public Object getmethod(){
getter s=new getter();
String app="apple";
s.setApp(app);
String ble="blue";
s.setGrp(ble);
String re="grape";
s.setGrp(re);
return s;
}
}
这是获取方法:
public class getter {
String app;
String org;
String grp;
String mn;
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public String getGrp() {
return grp;
}
public void setGrp(String grp) {
this.grp = grp;
}
}
这是测试类:
public class Check {
public static void main(String[] args) {
simple s=new simple();
getter g=new getter();
s.getmethod();
String first=g.getApp();
String second= g.getGrp();
String third=g.getOrg();
System.out.println("the value 1st is " + first + "the second" +
second +"3rd is"+third);
}
}
这就是我得到 null 作为值的地方。
最佳答案
here i am getting null as the value
您正在打印新的getter
变量,这些变量尚未设置,因此它们都是空的。
就其本身而言,s.getmethod()
将调用该方法,并创建一个新的 getter(与您之前创建的不同),但不会返回任何内容,因此您需要进行赋值。
getter g=(getter)s.getmethod();
如果您不想进行强制转换,请更改方法以返回 getter 而不是 Object
public getter getmethod(){
所以你可以这样做
getter g=s.getmethod();
关于java - 请解释一下该方法中的gettersetter_method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498574/