Reputation: 9850
i want to access the arr
variable from inside the inner class method MyMethod
. When i try to print it from there i end up getting a null pointer exception.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
my = new MyClass();
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
my.arr=n;
}
}
Upvotes: 0
Views: 3616
Reputation: 8195
You haven't initialized it yet, so the reference is null
. Initialize it in your constructor for example, and you will have access to the variable via your inner class.
public class MyClass {
String[] arr;
public MyClass (String[] a_arr) {
arr = a_arr;
}
public class MyInner {
public void MyMethod () {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main (String[] args) {
String[] n= {"ddd","f"};
MyClass myClass = new MyClass (n);
}
}
Upvotes: 1
Reputation: 3871
Do the following. Your way of initialization is wrong.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
MyClass my=new MyClass();
String[] b = new String[2];
System.arraycopy( n, 0, b, 0, n.length );
}
}
In case of more than 2 strings, simply do String[] b = new String[n.length];
Upvotes: 0
Reputation: 5537
Well, for starters in your main method you never create an instance of your class.
Also, MyClass
has a reference to a MyClass
object. In the constructor of MyClass
, it initializes that reference by calling it's own constructor. That's an endless loop.
Upvotes: 0
Reputation: 533492
You can use just arr
. However until you set it to something it will be null
BTW: Your my = new MyClass()
will blow up as it will create objects until it stack overflows.
Upvotes: 3