Question

I am trying to understand the usage of Java extend.... I created a sample testing code to under how it works....

public class Parent {

    public String Msg="Original";

    public String getMsg() {
        return Msg;
    }
    public void setMsg(String msg) {
        Msg = msg;
    }

    public void printing(){
        System.out.println(Msg);    
    }
}

public class Child extends Parent{

    public HashMap<String, String> Msg2;

    public Integer Msg3;

    public HashMap<String, String> getMsg2() {
        return Msg2;
    }
    public void setMsg2(HashMap<String, String> msg2) {
        Msg2 = msg2;
    }

    public void printing(){
        System.out.println("1 : " + Msg);
        System.out.println( Msg2 );
    }


    public static void main(String[] args) {

        Child a = new Child();

        System.out.println(a.Msg.getClass());  // able to detect variable from parent

        System.out.println(a.Msg2.getClass()); // Not able to detected, even variable from                  
                               // same instance object child    
        System.out.println(a.Msg3.getClass()); // Not able to detected, even variable from                  
                               // same instance object child


        a.printing();

    }

}

I getting confuse why Msg variable from parent object can detected easy.

While Msg2 and Msg 3 coming from the same instance Child -> a can't recognize it's own variable.

The error message getting from Msg2 or Msg 3 is, Exception in thread "main" java.lang.NullPointerException

Is there anyone able to explain why java behave in such way ?

Thank you....

Was it helpful?

Solution

You have not initialized Msg2 and Msg3. You need to use the new keyword to initialize them, so that they are not null.

add these two statements.

Msg2 = new HashMap<String,String>();

Msg3 = new Integer();

OTHER TIPS

Because Msg has been initialised to a non-null value (the string "Original") but the other fields have not, so they're null and you get an exception trying to call a method (getClass) on a null reference. If you just tried to print out Msg2 rather than Msg2.getClass() then you'd see the value null with no exception.

first set a value to your msg in your child class so its not null by default.

 Int Msg3 = 5;

and display it this way

System.out.println("Here is a msg:" + child.Msg4);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top