By Tony Bevis on Saturday, 16 September 2023
Category: Java

Java programming course: 1.8 Example Java class to model an animal

This is Lesson 1.8 of the Java programming course.

Example Java class to model an animal

Earlier a class called Animal was specified capable of storing an animal's name, gender and age, and also capable of providing that information upon request. You will therefore start to write the Java source code for such a class. This new class, along with other related classes you will also develop in this course to represent zookeepers and visitors, can be thought of as being part of the core system of the zoo application. For reasons which will become clear later, it is useful to separate the core system classes (which are non-graphical) from those which will be part of the graphical user interface[1]. You will therefore create two sub-packages under virtualzoo called core and ui to contain these classes respectively.

Right-click on the virtualzoo package node, select New | Java Package... and enter virtualzoo.core in the Package Name entry field:

[1] You will start to develop the graphical user interface starting in Section 16.

Click the Finish button. Now repeat the same process by right-clicking the virtualzoo package node again and creating another package called virtualzoo.ui, after which the IDE should look like that shown below:

Ensure your package structure matches that in the illustration above before continuing. To summarise, you currently have three separate packages which will be used throughout this course for the following purposes:

Even though core and ui are sub-packages of virtualzoo you should still think of them as being separate packages from virtualzoo in their own right.

You are now in a position to create the Animal class, so right-click on the virtualzoo.core package node, select New | Java Class... and enter the class name Animal into the Class Name box:

When you click the Finish button a new tab will appear for the Java source code for the new class:

The source code for Animal currently looks like this:

You will recall that so far there are three required attributes (i.e., name, gender, and age) and three behaviours (i.e., being able to provide each of the three attribute values to other objects that can make use of it).

Declaring attributes

​The attributes of a class are stored in instance variables.

You can think of a variable as being a storage location for a value of some kind. In Java there are two categories of variable, as follows:

Primitive variables: This kind of variable holds values directly. The most used primitives are:

Reference variables: This kind of variable holds a reference, which you can think of as a "pointer") to an object (i.e., an instance) of a class. This could be either an object of a class supplied with Java or an object of a class that was written by you or someone else. Some example Java supplied classes are:

[1]Named after George Boole, an English mathematician.

[2]Some other languages allow numerical values for boolean types (e.g., 1 for true and 0 for false) but Java does not allow this. You therefore cannot use booleans in arithmetic computations.

Note the different naming convention to distinguish between primitive and reference types; primitive types start with a lower-case letter (e.g., int) while reference types start with an upper-case letter (e.g., String). This is because reference types are always classes, which should start with a capital letter according to Java conventions.

While most of Java revolves around classes and objects, primitive types exist primarily for efficiency reasons for frequently used numerical and logical types.

When you declare an instance variable you have to decide which type to use; firstly, whether it should be a primitive or a reference type, and then which specific primitive or reference type. An animal's name is always a string of characters, so the String class would be a natural choice. An animal's age, measured in whole years, would most readily be stored using the primitive int type. For an animal's gender you will, for the time being, also use a String (which will be either "m" or "f").

Type the statements marked in bold below inside the class block part of the Animal source file:

You will now define a constructor for the class. Constructors are used to create individual instances (i.e., objects) of the Animal class to represent each separate animal that you need to do something with. When creating an instance, you can also specify the initial values of its variables. Add the statements marked in bold:

So far, you have written a class which is capable of instantiating (i.e., creating) one or more objects (i.e., instances) of the Animal class, and you can supply the values for each instance.

To show how you could use this new class, modify the VirtualZoo class as follows (changes marked in bold):

Note the following:

It is very common to combine the two declaration and instantiation statements into a single line, as follows:

You can run this application right now (by clicking the green arrow button in the toolbar) and the Output window should show that it completed successfully:

The Animal object referenced by bruno existed for the duration of the run and was then discarded when the program ended.

At this stage, of course, the program is not very useful as there is currently no way of getting the values out since the instance variables were declared to be private.

You will now add the functionality needed to retrieve the data from each instance.

Declaring Java functionality

The behaviours of a class are defined by writing methods[1], where each method performs one piece of functionality. In an application, different objects send messages to each other, where each message results in a method being invoked. Some methods retrieve and return information while other methods might perform some internal processing such as modify some data.

You will now write a method to retrieve the animal's name. In the Animal class add the lines marked in bold:


[1]
In some other languages methods are known as functions. Java always uses the term method.

You will now define two additional methods to return the gender and the age:

The getGender() method is very similar to getName() except that it returns the gender instance variable, which is also an object of type String.

The getAge() method is likewise similar, returning the int value of the age instance variable.

Trying out the new methods

Modify the VirtualZoo class to invoke the three methods you just defined after the bruno object has been instantiated:

The statement String brunoName = bruno.getName(); causes the getName() method to be invoked upon the bruno object. Since this method returns a String you need to assign it to a String object, which here is called brunoName:

The statement System.out.println(brunoName); sends a line to the Output window containing the textual value of the variable brunoName.

If you run the project, you should see the following in the Output window:

It is possible to combine the invocation of the getter methods inside the statements which send to output:

The way the above works is by processing methods from the inside out; that is, the inner most pair of brackets relates to the getName() method, which is nested inside another pair of brackets which relates to the println() method. The processing follows this sequence:

  1. The getName() method is invoked upon the bruno object reference.
  2. The getName() method returns a String reference (for the animal's name).
  3. The String reference returned becomes the argument to the Java supplied println() method, so assuming the String "Bruno" was returned it would have the effect of doing this: System.out.println("Bruno");
  4. The String Bruno is sent to the output window (which is what the println() method does).

You can enhance the output by combining the variables with some explanatory text:

Note how you can use the + operator to concatenate together pieces of text, so the output should now show:

You can create as many Animal objects as you like:

Each object so created has its own independent state (i.e., set of instance variable values), so you need to specify which one when invoking a method upon it:

As you have seen, you can name your objects anything you like, but it makes sense to use names which directly relate to the object, and which are easily remembered.

​Building your projects

​When you run your projects, NetBeans will automatically recompile any updated Java class files for you. Sometimes, however, it is helpful to run the compilation process without running the project, perhaps just to see if you have any errors. To do this, right-click on the VirtualZoo project node and select Clean and Build. Alternatively, there is an icon on the toolbar that looks like a hammer and brush that performs the same action.

You may want to clean and build your projects periodically as you work your way through this course. Make sure the last line of the Output window says BUILD SUCCESSFUL. If the build failed, then there will be some preceding lines pinpointing the classes and statements that are in error.

​This completes Section 1. In Section 2 we will cover object-oriented concepts.

Lesson 2.1 Object-oriented concepts

Related Posts

Leave Comments