JaVa
   

Introduction to Object-Oriented Programming (OOP)

The transition from a procedural coding (non-OOP) language to an object-oriented coding language is a large step for many programmers. It is true that both methods of coding can ultimately achieve the same goals, but you will find OOP is a neater and faster way to program, it is more suitable for teamwork, and programs are usually easier to design using the object-oriented approach. With OOP in Java, you will find that coding is challenging to begin with, yet very easy and very rewarding once you master it.

What Is an Object?

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 related to the alien and also contain functionality associated with it. You can include data such as the number of lives the alien has and also the functionality to affect the data, such as code to kill the alien, which could remove one of the lives.

The essential elements that make up an object are variables and methods. Variables are data members, or attributes, that contain data relating to the object, such as a text string or numeric value. Methods provide the functionality of the object and can be used to interact with the attributes. Methods are also known as functions or procedures in various other coding languages.

Object-Oriented Programming in Java

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 , "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 parts: constructors, attributes (properties), and methods. 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 follows, which can be used to change the value in age:

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.

Constructors

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 name as the class in which it is contained and cannot have a return value (we will look at return values in the "Methods" section toward the end of this chapter). We will now add two constructors to the Person class:

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 next chapter. 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 user-defined constructors.

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 term used to describe the creation of an object or instance of a class. The following diagram will hopefully help you understand this a little better, as it shows the relationship between the Person class and objects created from it.

Java Click To expand
Screenshot-1:

Class Members and Object Members—The static Keyword

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 otherwise it does not exist. The example we have just seen creates an instance of the class Person referenced by billyGate. We could have also created many more instances of the Person class. Suppose we said that the billyGate object was the only person that we would ever need or want to create; then we could scrap the Person class altogether and simply create a new class called BillyGate instead.

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. Screenshot-2 illustrates the relationship between the Person class containing class members and object members and the objects created from it.

Java Click To expand
Screenshot-2:

References

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 illustrated in Screenshot-3 by seeing what Screenshot-2 would look like after the above code is implemented.

Java Click To expand
Screenshot-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 for more detail).

Now let's get something compiling, finally!

JaVa
   
Comments