accounts is a reference to an array of Account objects.
is an abstraction of an Account in the form of a class.
Note: there is an example of method overloading here.
Here is the code in another class, Main, which constructed the above array of Account objects:
Account[] accounts = new Account[9];
A method in the class Main, countRich, will process the array, accounts.
It will return a count of all Accounts which have a balance greater than the parameter balance
Let's assume that accounts is a global variable and visible to all methods in the Main class.
Complete the code to process the array:
public static countRich(double ){
int count = ;
for(int i = 0; i<accounts.; i++){
if(accounts[]. > balance){
count = count + 1;
}
}
return
}
If we compile this program, we will not get a compiler error.
However, if we run this program, we might get a runtime error.
This is because if there is a null in the array, then the if statement will crash the program.
For example, look at the animation above.
accounts[3] references null (digital nothing, a convenient placeholder if an object is not available).
so accounts[3].getBalance() cannot be executed because null does not have a getBalance() method associated with it!
Especially when processing arrays of objects like Accounts or Strings or Elephants or... we need to write code to check for null.
To fix the above problem, we need to make the if statement a bit smarter:
if(accounts[i]!=null && accounts[i].getBalance() >balance){
Note: the check for null has to happen before further processing.
Because we are using AND logic, if the first statement if false, Java will not bother to execute the second half of the statement because false and anything is false...
When code, for example a method, processes an array of objects, it is more than likely that the array will have nulls in it.
Attempting to process an array without checking for nulls may result in a runtime error!
Runtime errors are very awkward because they can happen after successful compilation of the program (just when we assume everything is fine!)
This is why thorough testing eg is extremely important when designing computer programs.
Click the exercises button and see if you can complete the challenges.
object
property
method
create an object/instance of a class
instantiate an object
encapsulate
access
mutate
abstraction
methodsyntax overriding overloading instantiate instance super parameterattribute