Q:

initialize member variable of base class inside child class and use in other class

Hi i have a Base class containing one string member as belows :
public class BaseClass 
{
    public String test;
}

Child class extending base class where i wish to initialize the test value.
public class ChildClass extends BaseClass 
{
    public void initialize()
    {
        System.out.println("inside constructor of ChildClass.");
        this.test="stringtest";
    }
}

Test class where i wish to use the value of test variable of base class:
public class TestClass extends BaseClass 
{
    public void test() 
    {
        new ChildClass().initialize();
        System.out.println(this.test);
    }
    public static void main(String[] args) {
        new TestClass().test();
    }
}

Now my above code is printing null inside test class. why so? although i have initialized the test variable in child class? am i going wrong somewhere in java concepts?

A:

the problem is that you create new ChildClass but you aren't setting it in a variable. then you print this.test which is never set.
when you are in test method you are in TestClass instance:

you are creating and setting a ChildClass class

but then you are printing the TestClass test member

if you just want to create ChildClass and use it do
public class TestClass
{
    public void test() 
    {
        ChildClass cls =new ChildClass().initialize();
        System.out.println(cls.test);
    }
    public static void main(String[] args) {
        new TestClass().test();
    }
}

or if you want to extend ChildClass do
public class TestClass extends BaseClass 
{
    public void test() 
    {
        initialize();
        System.out.println(this.test);
    }
    public static void main(String[] args) {
        new TestClass().test();
    }
}

