Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用接口隐藏实现细节_Java_Interface - Fatal编程技术网

Java 使用接口隐藏实现细节

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

我有一个包含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 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();

在测试类的第一行。

在静态方法中设置私有实例字段?