Java Tutorial 2: Creating a Basic Class

In the first tutorial, we saw how you can create a basic java program, and we discussed the 'primitive' data types.

In this tutorial, we'll expand the original program a little to create an object from the basic class.

In object-oriented programming, a program is thought of as being composed of various interacting "objects". Objects are made from templates called classes, and each class will typically define both some data and some methods, which are basically procedures containing code that implement the behaviour of the class.

Let's enlarge the basic program from Tutorial 1 to actually create a new object from the class we define.

public class Animal {
    public static void main(String [] args) {
        Animal animal = new Animal();
    }
}




This program outputs nothing. Like our previous programs, it defines a class (called "Animal"). When you compile this code and run it, Java will look for the 'main' method and execute it (it makes no difference whereabouts in the class this 'main' method is located, but the class must have one if you want to execute it as a program). The main method then declares a variable of type 'Animal'; it then uses the new keyword to create a new object of the 'Animal' class type, and assigns it to the variable.

Let's add some data to the Animal class. We'll add a String variable containing some data. We will also add a 'method' called 'speak' to the class. The method will implement some behaviour for the Animal class; namely, it will display the string we're going to add. Note that the method looks a bit like the 'main' method. The 'main' method is really just a specially-named method, declared 'static' (more of this later on).

Although this may seem complicated right now, it will become a lot clearer as you gain more familiarity with Java and practice creating your own classes.


public class Animal {

    // Declare and initialize some String data.
    private String voice = "meouww";
    
    public static void main(String [] args) {
        
        // Declare a variable called 'animal' of the type 'Animal'.
        // Initialize the variable with a new 'Animal'.
        Animal animal = new Animal();
        
        // Call (run) the speak() method.
        animal.speak();
    }
    
    // Define a 'speak' method, which does nothing but
    // print (i.e. display) the String data.
    public void speak() {
        System.out.println(voice);
    }
}




meouww




Note that the String instance variable (i.e. the String variable attached to the Animal object) is declare 'private'. This means we cannot access this variable from outside the class. We cannot, for instance, write:

// Not allowed; voice is declare private
System.out.println(animal.voice);




... but we CAN write:

// Allowed; speak is declare public.
animal.speak();




... because the speak() method is declared public, and so is available from outside the class.

Constructors



Often you want some initialization code to run when an object is created from a class. You can do this using a special method called a constructor. The constructor runs when an object is created. The constructor must have the same name as the class and it must be declared public; it must not have a return type (we haven't covered return types yet!).

Here we've changed the example so that the constructor runs some code. Most often though, a constructor is simply used to initialize instance variables (initialize means to give the variables actual values). In many cases we can also, alternatively, initialize instance variables at the same time that we declare them, before the constructor even runs. We've done that with our private 'voice' variable, assigning it the value 'meouww'.


public class Animal {

    // Declare and initialize some String data.
    private String voice = "meouww";
    
    // This is a special method called a 'constructor'.
    // It runs automatically when any object is created
    // from the class.
    public Animal() {
        System.out.println("Constructor running!");
    }
    
    // The program starts here, even though this is by no
    // means the first line in the file, or even in the class.
    public static void main(String [] args) {
        
        // Declare a variable called 'animal' of the type 'Animal'.
        // Initialize the variable with a new 'Animal'.
        Animal animal = new Animal();
        
        // Call (run) the speak() method.
        animal.speak();
    }
    
    // Define a 'speak' method, which does nothing but
    // print (i.e. display) the String data.
    public void speak() {
        System.out.println(voice);
    }
}




Constructor running!
meouww




Some Notes on Strings



We've used the String type to hold string data before displaying it. In fact, whenever you type two speech marks in Java and assign them to a string, you are creating a new String object. This is a very handy shortcut built into Java.

You can also add strings together using a plus sign.

However, beware! In situations where memory or processing power is tight or you're inside a loop with lots of iterations, you must always remember that typing two speech marks and assigning them to a string, or adding them to an existing string, actually creates a new String object, and String objects are fairly substantial objects.

Here's a program that illustrates the point.


public class Animal {


    // The program starts here
    public static void main(String [] args) {
        
        // Declare a variable called 'animal' of the type 'Animal'.
        // Initialize the variable with a new 'Animal'.
        Animal animal = new Animal();
        
        // Call (run) the speak() method.
        animal.speak();
    }
    
    
    public void speak() {
        
        // This looks harmless and is not unreasonable, but keep in mind
        // that each time we use the + we are creating a new string, NOT
        // simply increasing the size of the existing string.
        String sum = "hello" + " " + "there";
        
        System.out.println(sum);
        
        // In fact the above code is equivalent to the following:
        
        // Declare and initialize some strings.
        String string1 = "hello";
        String string2 = " "; // This string is just a space
        String string3 = "there";
        
        String sum2 = string1 + string2 + string3;
        
        System.out.println(sum2);
    }
}




hello there
hello there