Java Reference
In-Depth Information
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
1. class ClassA{
2. // instance Members
3. int i ; // instance variable
4. void methodA(){// instance method
5. // do something
6. }
7. }
i is an instance variable of type int , and int is the primitive
data type of i .
In line 4,
In line 3,
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
1. class ClassA{
2. static int i ;
3. static void methodA(){
4. // do something
5. }
6. }
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.
 
Search WWH ::




Custom Search