1

I have two public classes class A and class B in two different packages.

So when I try to initialize class B inside class A, it throws a null pointer exception. Something like :

public class A {
  class B = new class B();
}

Infact I have to initialize it inside a method to use it. Example :

public class A {
 public void method(){
  class B = new class B();
 }
}

I know I am missing something here, but need an urgent help on this

2
  • Check if you can do the same with two classes in the same package. Commented Sep 5, 2022 at 6:41
  • Also... what's the exact text of the exception? Commented Sep 5, 2022 at 9:49

2 Answers 2

0

Edit: You should have a constructor

Like:

public class A {
  public B theB;
  public A(){
    this.theB = new B();
  }
}

But you can use an implicit one like this:

public class A {
  public B theB = new B();
}

You hadn't named your class member variable, hence you were getting strange errors. In fact... I'm surprised it compiled.

2
  • nope, not working Commented Sep 5, 2022 at 4:35
  • 3
    Well, there's no way this will ever work: class B = new class B(); because you are not assigning it to a variable. Are you perhaps leaving out too many details and obscuring the problem? Commented Sep 5, 2022 at 4:53
0

You are obscuring/simplifying too much for me to be sure, but in order to initialize a class don't forget it still is a variable.

public class A {
  public classB nameForB = new classB();

  //class A methods
}

Or if you want B to only be initialized upon the initialization of A (which is safer imo)

public class A {
  public classB nameForB;

  public A(){
    nameForB  = new classB();
  }

  //class A methods
1
  • 1
    Given that nameForB is an instance variable in both cases, both of your approaches would not initialize/instantiate that variable until an instance of A is created. There should be no difference. Like you said though, OP has changed their example code too much for us to be able to know what the actual problem is. Commented Mar 9, 2023 at 11:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.