0

I have below class

public class xyz {
    public class demo {
        String name;
    }
    public class test {
        public demo dd;
        public string check;
    }
}

In my controller I am using below method

xyz.test obj = new xyz.test();
obj.dd.name = 'test Name';

this lines gives me null pointer exception. Can someone tell me why? and how to remove it?

1

You need to instantiate your dd object before you can use it.

xyz.test obj = new xyz.test();
obj.dd = new xyz.demo();
obj.dd.name = 'test Name';
2

As it stands you have no constructor (not needed but.....) and are not instantiating dd

You need to either

  1. Explicitly instantiate dd

    xyz.test t = New xyz.test();
    t.dd = New xyz.demo();
    t.dd.name = 'Test Name'
    
  2. Instantiate demo when you instantiate test (constructor)

    public class xyz {
      public xyz(){
         demo = new demo();
      }
      public class demo {
        String name;
      }
      public class test {
        public demo dd;
        public string check;
      }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.