使用抽象方法时,defined var为null

use*_*497 2 java methods android class abstract

我有class A一个abstract method,并class B延伸class A.

abstract method 在创建新的类对象时调用.

class B我已经定义一个全局变量,但是当我尝试使用这个变量似乎为空.理论上,这var是定义和初始化的.

我的代码:

public abstract class A{

public abstract void someMethod();

public A(){
    someMethod();  
}

}


public class B extends class A{
 Rectangle[] mPathDots=new Rectangle[30]; //initialized array with 30  nulled items

 @Override
 someMethod(){
   int x = mPathDots.length; //error! mPathDots is null, but in theory lenght must be 30 !?
 }
}
Run Code Online (Sandbox Code Playgroud)

创建:

B b = new B();
Run Code Online (Sandbox Code Playgroud)

为什么是mPathDotsnull?
我尝试创建一个class B没有的对象abstract method,它没有任何问题,但是abstract methodvar是没有问题的.

Cod*_*ice 6

你得到a的原因NullPointerException是因为new B()先调用构造函数A 然后调用构造函数B.B直到第二个构造函数调用的最开始时才会初始化字段.

建议:

一种可能的解决方案是简单地将代码移动someMethod()B构造函数:

public class B extends class A{
 Rectangle[] mPathDots=new Rectangle[30]; //initialized array with 30  nulled items

 public B(){
   int x = mPathDots.length; //error! mPathDots is null, but in theory lenght must be 30 !?
 }
}
Run Code Online (Sandbox Code Playgroud)