[Solved] How to pass value from protected method to a public method?


Just tried to guess your code. Please find bellow explanation

public class Main {
    String str = null;
    public static void main(String[] args) {
        Main m1 = new Main();
        m1.setTheValueHere();
        m1.getTheValueHere("called by m1");

        Main m2 = new Main();
        m2.getTheValueHere("called by m2");
    }

    protected void setTheValueHere(){
        str = "hello";
    }

    public void getTheValueHere(String objName) {
        System.out.println(objName +" --- "+str);
    }
}

O/P :

called by m1 --- hello
called by m2 --- null

Here the String str is an instance variable. For object m1, hello got printed since both set and get method is called by the same object m1. The value set by m1 is not available for object m2 since it is different object instance, hence for m2 null is printed.

If you change String str to static variable as static String str = null; the output will be

called by m1 --- hello
called by m2 --- hello

because it is now class variable and hence shared to all the instances of that class.

Please check this explanation, you may get some idea about your problem.

solved How to pass value from protected method to a public method?