Top
Previous Next
Java's Object Orientation, I/O CS 161 - Java

Methods

Instance Methods

Instance methods are only called through an object: an instance of some class created by invoking new on a class.
 someInstance.instanceMethod()
Source: examples/Counter.java



/** An example of a class defining counter objects.
**/
 
public class Counter {
 
private int count = 0; // instance variable
 
public void increment() { // instance method
count++;
}
 
public int getCount() { // another
return count;
}
 
// for stand-alone testing
public static void main(String[] args) {
 
Counter[] cArray = new Counter[5];
for (int i = 0; i < cArray.length; i++ ) {
cArray[i] = new Counter();
for (int num = 0; num < 10; num++) {
cArray[i].increment();
}
}
 
for (int i = 0; i < cArray.length; i++) {
System.out.println("cArray[" + i + "] = " + cArray[i].getCount());
}
// What is output from the above?
}
}

Class methods

Utility methods associated with an entire class, not any one particular instance of the class.
 ClassName.classMethod()

Qualifying a method with the keyword static makes that method a class method.

Source: examples/ClassCounter.java



/** An example of a class that defines several class methods.
**/
 
public class ClassCounter {
 
private static int count = 0; // a class variable
 
public static void increment() { // class method
count++;
}
 
public static int getCount() { // another
return count;
}
 
public static void main(String argv[]) {
 
// The normal way to call class methods, from within the class
// or from some other class is:
// Classname.methodname( [arguments if any] );
 
// Even if I make instances of the class, and call the static
// methods through the instance references, the results are
// not going to work the same way that instance methods would.
 
ClassCounter[] cArray = new ClassCounter[5];
for (int i = 0; i < cArray.length; i++ ) {
cArray[i] = new ClassCounter();
for (int num = 0; num < 10; num++) {
cArray[i].increment();
}
}
 
for (int i = 0; i < cArray.length; i++) {
System.out.println("cArray[" + i + "] = " + cArray[i].getCount());
}
// What is output from the above?
}
}

If you find yourself using a lot of class methods in Java, it is a sign that you are thinking in the old, procedural programming style, not like an object oriented programmer.


Top
Previous Next
jwd