Constructors Part 1 Tutorial

A constructor is an important part of every class and it provides a way to execute statements as an object is created. The topic of constructors is quite extensive and describing many of the features of a constructor requires advanced topics that I haven't covered in my tutorials thus far. A constructor resides inside of the class body and at bare minimum it consists of the exact class name followed by a pair of parenthesis and a pair of curly braces.
Simple empty constructor structure:
class className {
      className() {
      }
}
Every class has to have a constructor whether you write one or not. If you do not write a constructor into your class, the java compiler will insert in a default constructor into the compiled bytecode. The default constructor is special and I will discuss it in a separate tutorial. In this tutorial I will create a constructor for my Acme class and have it display a string literal to the console.
This is going to be a short tutorial because my next tutorial will be discussing the new operator. Understanding the new operator is critical to moving on to the next constructor concepts.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md ConstructorsOne
C:\Java>cd ConstructorsOne
C:\Java\ConstructorsOne>Notepad ConstructorsOne.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class ConstructorsOne {
    public static void main(String args[]) {
        Acme a = new Acme();
    }
}

class Acme {
    Acme() {
        System.out.println("This code statement executed when the Acme object was initialized!");
    }    
}

Now switch back to the command prompt (CMD) and type in javac ConstructorsOne.java and press Enter.
Now type in java ConstructorsOne and press Enter.


C:\Java\ConstructorsOne>javac ConstructorsOne.java
C:\Java\ConstructorsOne>java ConstructorsOne
This code statement executed when the Acme object was initialized!


Final thoughts

As you can see, the constructor is used to execute statements as the object is being initialized. Now be sure to watch my next tutorial on the New Operator. After that tutorial is complete, I will pick back up with the next part of the constructor tutorials.


Tutorials