Friday, May 20, 2011

Your Own Java Classes

To use Java effectively, you want to create and use your own classes. This is one of the great powers of object-oriented languages--the ability to construct programs out of independent building-blocks that cut large problems down into small, easily solvable ones. There's a lot more that can be said, and much of it is elsewhere. So I'll get right into a very simple, very basic example here.

We're going to create a very simple object class that will print a "Hello" message to the screen when called. This class will have two different methods that will do the same thing, though we'll vary the messages they print a bit so that we can see which one is doing the work.

Here's our class: (download HelloClass.Java)

public class HelloClass{

* sayHello() prints "Hello!" to the Java console output.
public void sayHello(){

* doHello() prints "Hello, hello!" to the Java console output.
* It's static, so you don't need to instatiate a HelloClass
* object to use it.
public static void doHello(){
System.out.println("Hello, hello!\n");

} // End of HelloClass

The two methods we have to print messages are sayHello() and doHello(). To use sayHello(), we need to have a HelloClass object created, then call that object's sayHello() method.

doHello(), however, is a static method. This means is belongs to the class, not to any object of the class. So we can use it without any HelloClass objects being created first.

Here's a class that uses these methods as described: (download

public class UseHello{
public static void main(String[] arg){

// We can use doHello() without a HelloClass object:
HelloClass.doHello(); // call the HelloClass's doHello() method.

// But we need to create a HelloClass object to use sayHello():
HelloClass hello=new HelloClass();
hello.sayHello(); // call hello's sayHello() method.

} // End of UseHello.

If we try to call sayHello() without first creating a HelloClass object, like this:

then we'll get the dreaded "calling a non-static method from a static context" error message. That's letting you know that you need to instantiate (or create) a HelloClass object first, then tell that object to call its method.

Static methods are useful for things like general arithmetic and calculation or other methods that might be used in a way where state information is unimportant. But beware, it's easy to create static methods when what's really wanted is an object that does what you want.

Files available for download through: