访问通过引用的私有字符串

huangapple go评论66阅读模式
英文:

Accessing a private String through a reference

问题

我需要访问私有字符串中的消息,我认为可以通过使用引用轻松完成,但这会强制我插入一条新消息,这将替换以前的消息。

class Test {
    private String s = "This is string s";
    String methodS(String a) {
        a = s;
        return s;
    }
}

class name {
    public static void main(String args[]) {
        Test elen = new Test();
        System.out.println(elen.methodS("This is string s in another class."));  	
    }
}
英文:

I need to access the message in a private String, I though it could be done easily by using a reference, however it then forces me to insert a new message that will replace the backwards one.

class Test {
    private String s = "This is string s";
    String methodS(String a) {
	    a = s;
		return s;
	}
}

class name {
    public static void main(String args[]) {
        Test elen = new Test();
        System.out.println(elen.methodS("This is string s in another class."));  	
    }
}

答案1

得分: 3

你可以在你的类内部编写一个获取私有字段的getter方法。

String getS(String a) {
   return s;
}
英文:

You can write a getter method inside your class to get the private field.

String getS(String a) {
   return s;
}

答案2

得分: 1

你可以使用 getter 和 setter 方法来访问类的私有成员。

英文:

You can use getter and setter methods to access private members of a class

huangapple
  • 本文由 发表于 2020年10月4日 22:31:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/64195909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定