"All the world will be your enemy, prince of a thousand enemies."
— Watership Down
Hopefully you are all set up now and ready to execute some code of your own. In this chapter you will learn about the structure of the Java language with a variety of simple console programs. A console program is a program that is text based and looks similar to text entered in a command prompt window. The example programs in the early chapters of this book are console programs and are not visually attractive windowed applications or applets. We will keep it simple to start off with until you understand the nuts and bolts of the Java language.
The transition from a procedural programming (non-OOP) language to an object-oriented programming language is a large step for many programmers. It is true that both
Objects
are the building blocks that make up a program. It is difficult to explain exactly what an object is because an object can be anything you want. For example, you can create an object that represents an alien that can hold all information
The essential elements that make up an object are
The Java language is completely object oriented. This means that there are no global statements whatsoever (although static members can be conceived as being somewhat global—we will discuss static members later). Any attributes or methods must be defined as part of a class or interface. We will discuss interfaces in Chapter 4, "Multiple Classes," so do not worry about them for the time being.
A
class
in Java is used to define the structure of an object. A class can be broken down into three main
Let's now look at an example of a very simple class structure containing these three parts before we go any further. An example of a class could be a person, which could describe the attributes and methods that a person could have associated with them. An object can then be created from the person class, like you or me, or even your partner (if you do not have a partner, then well done; you are a true programmer).
In order to create an object, we must first create a class. Do not worry about compiling any of the code right now; just sit back, grab a coffee, and try to understand some basics.
Here is the beginning of our "Person" class:
class Person { }
Now, at the moment, we have the outline code for a Person class. First we should add some attributes. Let's add a numeric attribute to the class to store the age of a person.
class Person { int age; }
The keyword
int
stands for integer, representing a numeric data type, which is explained in more detail later on in the chapter. At this point, the
Person
class is all attributes and no functionality (clearly pointing to a career in politics). We can add a method to the class as
class Person { public void setAge(int newAge) { // set the age to the value stored in newAge age = newAge; } int age; }
Now we have a class called Person , containing one method called setAge and one attribute called age . The method setAge can be used to assign a new value to the age of the person. Again, do not worry too much about how methods work for the time being; your coffee should just be cool enough to drink about now.
In order to create an object (or an instance, as it is also known) from the Person class, a constructor must be invoked. All classes contain a default constructor, which does nothing and can be overloaded with many constructor types, as we shall see.
The
constructor
is a method that is called when the object is created and used to initialize the state of the object. The constructor must be declared with the same
class Person { public Person() { // basic constructor age is set to 0 by default } public Person(int newAge) { // contructor that sets the age to a specified value setAge(newAge); } public void setAge(int newAge) { // set the age to the value stored in newAge age = newAge; } int age; }
You can declare a reference to a Person object as follows:
Person billyGate;
At the moment, you have a reference to an object of type
Person
, which currently does not reference any object. The members of the object cannot be accessed, like the attribute
age
, because no object has been created. Note that the reference variable
billyGate
is actually equal to null at this point; the keyword
null
is discussed in the
A call to a constructor must be made to create a new object of type Person , assigning the variable billyGate to reference the new object.
If no constructors are declared for a class, a default constructor is available that takes no parameters and simply creates a default object of the class when invoked. In our code snippet we have created our own default constructor Person() , which contains no code, and a second constructor also called Person(int newAge) , which contains code that sets the value age in the Person object to a new age specified by a parameter value. We will look at parameters in the "Methods" section near the end of this chapter, so do not worry if you do not fully understand them.
| Note |
Had we only declared the second constructor and omitted the first constructor, there would no longer be a default constructor available that takes no parameters, as the default constructor only exists if the class doesn't contain any
|
To create an object from the Person class, we could use the following line of code:
// using second constructor, set age value to 21 Person billyGate = new Person(21);
This line of code declares an identifier called billyGate of type Person and creates a " new " Person object using the second constructor in the Person class to initialize the object, setting the age value in the new Person object to 21 .
We could also use the following code instead, this time using the first (default) constructor to initialize the object and then set the value of age using the setAge method, which is a member of the newly created object.
// use first constructor Person billyGate = new Person(); // use setAge member to set age to 21 billyGate.setAge(21); // set the value of age to 21
We can also access the age variable and set its value directly, as follows:
billyGate.age = 21;
| Note |
You cannot have two constructors with the same signature. We will see about method signatures in the "Methods" section toward the end of this chapter. |
So far we have seen
instantiation
, which is the
Figure 2-1:
I promise that this is the last bit before we start making some code that we can actually run, but it does need explaining. An
object member
is a member that is created when the object is created. This means it can only be accessed once the object has been created because
class BillyGate { public static void setAge(int newAge) { // set the age to the value stored in newAge age = newAge; } int static age; }
Notice that we have removed the constructors and added the static keyword to the two defined members. This is because we no longer need to create an instance of this class. We can just access the static members using the class name. For example:
BillyGate.setAge(21);
These static members are known as class members, whereas before we had object members.
The examples that we have used so far only contain either object members or class members; you can of course use both. Let's return to our Person class now and add a static attribute. The static attribute must be something that is going to be the same for all Person objects that we create. So we could add an integer variable called daysInAYear .
class Person { // code as before static int daysInAYear; }
We can access the attribute daysInAYear before we create any objects from the Person class. For example:
Person.daysInAYear = 365;
If we create new instances of Person , then they too can access the static variable daysInAYear .
Person glennMurphy = new Person(21); Person andrewMulholland = new Person(20); glennMurphy.daysInAYear = 366; // it is a leap year System.out.println(andrewMullholland.daysInAYear);
This code will create two new instances of Person , referenced by glennMurphy and andrewMulholland . The glennMurphy object then sets the static variable daysInAYear to 366 , and the andrewMulholland object will access daysInAYear , printing its value to the console window (this printing code will be explained later in the chapter). The number that will be printed to the console window is 366 , which means that daysInAYear does not belong to any of the objects alone; it belongs to all of them, and changes made from one affect the other. There is only one part of memory containing the value 366 to which they all refer. In short, it is the same attribute however it is accessed. Figure 2-2 illustrates the relationship between the Person class containing class members and object members and the objects created from it.
Figure 2-2:
To access objects (remember they are instances of classes) in Java, we use what are known as references . We have used three references so far in our code examples: billyGate , glennMurphy , and andrewMulholland . These were not the actual objects that we created but merely references (also known as handles ) to the objects created. Take the following code for example:
andrewMulholland = glennMurphy; // he'll never be my equal
This code simply makes
andrewMulholland
reference the same object that
glennMurphy
references; hence you could then access the same object using either of the two references. This is best
Figure 2-3:
The object with the age equal to 20 that andrewMulholland once referenced is now lost, but do not worry about freeing the memory; this is taken care of by Java's garbage collector (see the "Garbage Collection and Creating Objects" section in Chapter 12 for more detail).
Now let's get something compiling, finally!