[英]Deserialization of interfaces using Jackson, where the interface implementation is specified in the serialized object
[英]Using Interfaces to hide Implementation Details
我有一個具有1個界面和2個類的項目:-
public interface Account {
int add();
}
public class AccountImpl implements Account{
@Override
public int add() {
return 0;
}
}
和1種主要方法
public class Testing {
Account account;
public static void main(String[] args) {
Testing t = new Testing();
t.call();
}
public void call() {
int a = account.add();
}
}
我在int a = account.add();
行中得到了Null指針異常int a = account.add();
因為帳戶值為空。
我是Java新手,請您幫忙刪除它嗎?
在main
函數中call
,私有變量account
未初始化。 這意味着您永遠不會賦予它價值。 它不是指向一個對象(它是“空指針”,指向什么都沒有)。 因此,您不能調用該對象的方法。
要解決此問題,您將需要首先初始化變量。 例如,在您的Testing
類的構造函數中:
public Testing () {
account = new AccountImpl();
}
您尚未實例化要調用的AccountImpl
實例; 您得到的例外通常被稱為“您還沒有成為其中之一”。
public class Testing {
Account account;
public static void main(String[] args) {
Testing t = new Testing();
t.call();
}
public void call() {
account = new AccountImpl();
int a = account.add();
}
}
您尚未初始化帳戶。 您最好做這樣的事情。
Account account = new AccountImpl();
在Test類的第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.