0

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."));     
    }
}
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
  • What are you trying to do with the string you passing to the `methodS()` method? Why do you have such a string argument, you don't do anything useful with the string? Why don't you create a simple getter for the private field `s`? – Progman Oct 04 '20 at 14:35
  • I'm trying to pass and display the private String to the class name – Edoardo Fiorini Oct 04 '20 at 14:37
  • 1
    You might want to look at https://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work – Progman Oct 04 '20 at 14:39
  • Have you even tested your code? The string you pass as an argument to `methodS()` will not replace anything, because you don't assign the argument to anything. In fact, `methodS()` is already a getter and does exactly what you want. It also does a very useless replacement of the argument by the private string (not the other way around as you said in your question) that serves no purpose because the argument is not used, but that doesn't make it not work as you intend, it just makes the argument you pass to the method unnecessary. – JustAnotherDeveloper Oct 04 '20 at 14:43

2 Answers2

3

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

String getS(String a) {
   return s;
}
Eklavya
  • 17,618
  • 4
  • 28
  • 57
1

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

Diksha
  • 11
  • 1