英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论