Java 使用接口隐藏实现细节
我有一个包含1个接口和2个类的项目:-Java 使用接口隐藏实现细节,java,interface,Java,Interface,我有一个包含1个接口和2个类的项目:- public interface Account { int add(); } public class AccountImpl implements Account{ @Override public int add() { return 0; } } 和一个带有main方法的类 public class Testing { Account account; public stati
public interface Account {
int add();
}
public class AccountImpl implements Account{
@Override
public int add() {
return 0;
}
}
和一个带有main方法的类
public class Testing {
Account account;
public static void main(String[] args) {
Testing t = new Testing();
t.call();
}
public void call() {
int a = account.add();
}
}
我在inta=account.add()行中遇到空指针异常代码>因为帐户值为空
我是java新手,您能帮我删除这个吗?当在main
函数中调用call
时,私有变量account
未初始化。这意味着你从未赋予它价值;它不是指向一个对象(它是一个“空指针”,不指向任何东西)。因此,不能调用该对象的方法
要解决此问题,您需要首先初始化变量。例如,在测试类的构造函数中:
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();
在测试类的第一行。在静态方法中设置私有实例字段?