Java Keywords (Part IV): Classes and Objects

This is not a break in my Java Keyword series. This is a continuation of the series that focuses in two things. The first part will focus on the anatomy of a class, which I have covered (somewhat) already. The second part focuses in the concept of a class constructor. Lastly, and as a related topic to that second part is how to invoke class constructors and explains what happens when this occurs (which I have somewhat covered already). View this article as a way to tie loose ends before moving on to other topics.

In the end, I will wrap up the keywords class and the new operator.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.
Although the list above is arranged in alphabetical order, I will go through them in a different order.

What is a class?

The universal definition of the word "class" in Object-Oriented Programming, is the template from which objects are created. This template defines the type of object it can be. For instance,

public class Coin
{
    // internal details omitted
    public Coin() 
    {
        // Does something.
    }
}
is used to create objects of type Coin. We can clearly see in the class definition that it is a "class" because the keyword class is used. In Java, when designing classes, there are a few rules that we must observe.
  1. The name of the external class MUST match the name of the file. Therefore, this Coin class file must be named Coin.java
  2. The name of the class MUST match the name of the constructor. In the previous code example, you can see Coin() which is the class constructor. (More on constructors shortly)
  3. A class can contain infinite numbers of constructors. However, if none is explicitly defined, one will be added to the class at compile time.

What is a constructor?

A class constructor is a special method that
  1. Has the same name as the class (already mentioned)
  2. Does not contain a return type in the declaration
I mentioned before that a class will be given a constructor if it does not explicitly declare one. This constructor is known as the default constructor. The default constructor (if it were to be created manually) will look like this:

public Coin() {}
When a class declares the above constructor explicitly in the class, it is no longer a default constructor. It is called a no-argument constructor. Default constructor is a term reserved only for the constructor added to the class by the Java compiler. The two classes below are virtually the same. The first one, when compiled, will have a default constructor that will look exactly as the no-argument constructor included in the second version of the Coin class.

public class Coin
{
    private String material;
    private double coinValue;
    private boolean real;

    public void setMaterial(String value) 
    {
        material = value;
    }

    public String getMaterial() 
    {
        return material;
    }

    public void setValue(String value) 
    {
        coinValue = value;
    }

    public String getValue() 
    {
        return coinValue;
    }

    public void setReal(String value) 
    {
        real = value;
    }

    public String isReal() 
    {
        return real;
    }
}
Class with default constructor.

public class Coin
{
    private String material;
    private double coinValue;
    private boolean real;

    // No-argument constructor
    public Coin() {}

    public void setMaterial(String value) 
    {
        material = value;
    }

    public String getMaterial() 
    {
        return material;
    }

    public void setValue(String value) 
    {
        coinValue = value;
    }

    public String getValue() 
    {
        return coinValue;
    }

    public void setReal(String value) 
    {
        real = value;
    }

    public String isReal() 
    {
        return real;
    }
}
Class with no-argument constructor.
Once a constructor is explicitly defined in the class, the compiler will not add a default constructor to the class.

Notice in the class above that the body of the method is empty. The sole purpose of the default constructor is to create instances of the class with default values. Normally, when we define class constructors, we want the constructor to initialize the data members (variables) with specific values. So, what are these default values? When a class is created and using a default constructor, default values are assigned to variables as follows:

  1. Numeric primitives are assigned the value of zero (0).
  2. Primitive char variables are assigned the value of the null character (unicode '\u0000')
  3. Primitive boolean variables are assigned false
  4. Object references, such as String are assigned null. This means that an instance for that variable does not exist. In order to use object references in our programs, object references must be properly instantiated (created).
For the above classes, the constructor will create an instance of Coin with default values assigned. The variable declarations is the same as if I would have done the following:

public class Coin
{
    private String material = null;
    private double value = 0.0;
    private boolean real = false;

    // The rest omitted
}

As I previously mentioned, a class could contain multiple constructors:


public class Coin
{
    private String material;
    private double coinValue;
    private boolean real;

    // Constructor: sets the value of coinValue variable
    public Coin(double value)
    {
        coinValue = value;
    }

    // Constructor: sets the values of all variables
    public Coin(String value, double val, boolean isReal)
    {
        material = value;
        coinValue = val;
        real = isReal;
    }
}
In this example, the Coin class contains two constructors. However there is no "no-argument" constructor defined nor the compiler will add a default constructor to this class. The assumption is that, if the designer of the class decided not to include this type of constructor, it must be for a reason. Therefore, the Java compiler will not overrule this decision.

The new operator

This section will be short because there is really not much to it. The new operator is used to return, as the keyword implies, a new instance (object) of that class. The usage of this keyword is as follows:


    Coin myCoin = new Coin("Cupro-Nickel", 0.25, true);
    Coin yourCoin = new Coin("Cupro-Nickel", 0.25, true);
Even though the two coins are identical in every aspect, they do not represent the same object. Every time the new operator is invoked, a new area in memory is allocated to store the object that is about to be created; regardless if there is already another identical object in memory. This sounds wasteful. And it can be. For that, there are mechanisms in place that would prevent wasteful allocation of resources. This is very advanced topic and probably one I will not be writing about in the near future. For now, all you need to know is that the new operator creates new objects in memory of the type specified in the statement.

Summary

By now, you should have a basic understanding of how to design classes with constructors and how to invoke these constructors to create objects. This is the cornerstone of Object-Oriented Programming!

Comments

  1. Classes open new doors and applications for programming. The layman's understanding of creating a new class is creating a new data type. Think of the different data types such as int, float, double, string,... etc. They all have their own properties, capabilities, and limitations; but with the introduction of classes, it allows for one to create their own data type that has its own properties, capabilities, and limitations that are configured to the needs of the program or process.

    The capabilities of classes are "extended" when polymorphism is implemented. This allows for classes to share properties with "parent" classes - thus creating more intricate relationships between class objects and extending the potential for programming.

    ReplyDelete
  2. In my opinion, classes are one of the most interesting parts of programming. They give some kind of freedom to every programmer to create their own data type for their special needs, while at the same time,data defined in classes can be private or protected. Also, I like the idea of using abstract classes and inheritance, and creating a child classes which are usually more detailed than their super classes.

    ReplyDelete
  3. Classes allows the coder to make their own data types and give the coder to change it as he see fits. Also classes allows the coder to restrict or give access to other classes with protected and private. With inheritance capabilities we get child classes and parent classes, as this give even more functionalities to the coder.

    ReplyDelete

Post a Comment

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern