Rahul Padalkar Rahul Padalkar - 1 year ago 78
Java Question

Access values of variables set on runtime

Here's the scenario :

I have 3 classes Class A,Class B and Class C.Now I am calling a method defined in C with return type String in Class A. I am setting the return value to another String in Class A. Now in class B i am making an object of Class A and calling the String set in A using the object. IF you want to know the execution then first i am calling the method defined in C in a and then the String in B. But i am getting the string value a NULL in Class B.

Class C

Class C{
//method with return type as string
public String getString(){
return "Some String Here";

Class A

Class A{
public String s;
public void somemethod(){
C obj = new C();
s= obj.getString();

Class B

Class B(){
pubic void anothermethod(){
A obj = new A();
String ss = obj.s;

ss when printed gives null as its value. When I print s I get the correct string. Here's how i am calling from main class

  1. Method somemethod() from Class A

2.Then Method anothermethod() from Class B.

Sorry if my question is a bit noobish.

Answer Source

If your question is regarding how you're getting the null in ss, you never called somemethodon obj in anothermethod. Everytime you call anothermethod, you instantiate a new A, in which the String field s has never been initialized and is still null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download