APPENDIX A: Introduction to Java 385
instance methods. Instance variables and instance methods, which belong to objects, are called
instance members (see Listing A-6) to distinguish them from static members, which belong only to
the class.
Listing A-6. The Instance Members
- class ClassA{
- // instance Members
- int i ; // instance variable
- void methodA(){// instance method
- // do something
- }
- }
In line 3, i is an instance variable of type int, and int is the primitive
data type of i.
In line 4, methodA(){} is an instance method.
Static Members
Static members, declared with the keyword static, are the members that belong only to the class and
not to any specific objects of the class. A class can have static variables and static methods. Static
variables are initialized when the class is loaded at runtime. Similarly, a class can have static methods
that belong to the class and not to any specific objects of the class, as illustrated in Listing A-7.
Listing A-7. Static Members
- class ClassA{
- static int i ;
- static void methodA(){
- // do something
- }
- }
Unlike instance members, static members in a class can be accessed using the class name,
as shown here:
ClassA.i // accessing static variable in Line 2 of Listing A-7
ClassA.methodA(); // accessing static method in Line 3 of Listing A-7
Though static members in a class can be accessed via object references, it is considered bad
practice to do so.