简体   繁体   中英

Using Interfaces to hide Implementation Details

I have a project with 1 interface and 2 classes:-

public interface Account {
    int add();
}

public class AccountImpl implements Account{
    @Override
    public int add() {
         return 0;
    }
}

and 1 class with main method

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(); as account value is null.

I am new to java, can you please help to remove this?

When call is being called in the main function, the private variable account is not initialized. 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:

public Testing () {
    account = new AccountImpl();
}

You haven't instantiated an instance of AccountImpl to call; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM