Page 334 - Computer_Science_F5
P. 334
(2) Booleans it is false,
(3) Object references it is null.. Values can be assigned during declaration or within
the constructor. Static methods cannot declare instance variables directly;
they should be accessed using the fully qualified name within static methods. Chapter Five: Object oriented programming with Java
Program Example 5.2 shows an instance variable program:
FOR ONLINE READING ONLY
Program Example 5.2:
Java program to demonstrate instance variable
public class PlantTrees {
// Instance variable declared at class level but outside any method
int AfforTrees = 783;
public void digHoleMethod() {
// Accessing the instance variable within the method
System.out.println(“Afforested trees value: “ + AfforTrees);
}
public static void main(String[] args) {
// Creating an object of the class to access the instance variable
PlantTrees obj = new PlantTrees();
// Calling the method which uses the instance variable
obj.digHoleMethod();
}
}
(iii) Static variable in static memory, initialised at program
Class variables, also called static start, and discarded at program end. They
variables, are defined using the share the same visibility as instance
“static” keyword outside any method, variables and are often public for
constructor, or block. Only one instance accessibility. They default to 0, false, or
of each class variable exists, no matter null, similar to instance variables. Static
how many objects are created. Typically variables are accessed using the class
declared as public/private, final, and name and variable name. When declared
static, they act as constants with fixed public static final, they are constants and
values throughout the program’s named in uppercase. Program Example
execution. Static variables are stored 5.3 shows a static variable program.
325
Student’s Book Form Five
Computer Science Form 5.indd 325 23/07/2024 12:34

