[英]Using Interfaces to hide Implementation Details
I have a project with 1 interface and 2 classes:- 我有一个具有1个界面和2个类的项目:-
public interface Account {
int add();
}
public class AccountImpl implements Account{
@Override
public int add() {
return 0;
}
}
and 1 class with main method 和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();
}
}
I am getting Null pointer exception in the line int a = account.add();
我在
int a = account.add();
行中得到了Null指针异常int a = account.add();
as account value is null. 因为帐户值为空。
I am new to java, can you please help to remove this? 我是Java新手,请您帮忙删除它吗?
When call
is being called in the main
function, the private variable account
is not initialized. 在
main
函数中call
,私有变量account
未初始化。 That means that you never gave it a value; 这意味着您永远不会赋予它价值。 it's not pointing to an object (it's a “null pointer” pointing to nothing).
它不是指向一个对象(它是“空指针”,指向什么都没有)。 As such, you cannot call a method of that object.
因此,您不能调用该对象的方法。
To fix this, you will need to initialize the variable first. 要解决此问题,您将需要首先初始化变量。 For example in the constructor of your
Testing
class: 例如,在您的
Testing
类的构造函数中:
public Testing () {
account = new AccountImpl();
}
You haven't instantiated an instance of AccountImpl
to call; 您尚未实例化要调用的
AccountImpl
实例; the exception you are getting could commonly be referred to as 'you didn't make one of those yet'. 您得到的例外通常被称为“您还没有成为其中之一”。
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();
}
}
You have not initialized the Account. 您尚未初始化帐户。 You would better do something like this.
您最好做这样的事情。
Account account = new AccountImpl();
at the very first line of the Test class. 在Test类的第一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.