[英]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.