以這個基類:java虛擬方法:功能還是bug?
public abstract class XMPPSubservice
{
protected XMPPService mTheService;
protected XMPPSubservice(Context context)
{
Intent intent = new Intent(context, XMPPService.class);
context.startService(intent);
}
public void onServiceInstance(XMPPService service) {
// TODO Auto-generated method stub
mTheService = service;
}
}
而這個派生類:
public class PublicDataSubservice extends XMPPSubservice
{
private final SomeObject mObj = new SomeObject();
public PublicDataSubservice(Context context) {
super(context);
}
@Override
public void onServiceInstance(XMPPService service)
{
super.onServiceInstance(service);
mObj.doSomethingWith(mTheService);
}
}
的目標是隻調用mObj.doSomethingWith(mTheService); mTheService成爲有效後(發生在基類中)之後。事情總是在mObj線爆出NPE。我可以理解爲什麼會發生這種事,但對我來說看起來很不自信。那麼這是DVM的缺陷還是功能? JVM如何?
有關調用來自構造函數的重寫方法導致的各種問題的更多示例,請參閱構造函數中的Josh Bloch的_Effective Java_ – user949300
>>虛方法。啊!......我以前在哪裏聽過?也許在大學裏。好的提醒!雖然Android讓它變得不那麼明顯,但我正是這麼做的。 – kellogs