Constructors Part 2 Tutorial

In this tutorial I will be adding some parameters to a constructor declaration. Once I add parameters to the constructor it is going to look very similar to a method declaration. The only difference between a constructor declaration and a method declaration is that the method declaration requires a return type. A constructor cannot have a return type.



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 ConstructorTwo
C:\Java>cd ConstructorTwo
C:\Java\ConstructorTwo>Notepad ConstructorTwo.java

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


class ConstructorTwo {
    public static void main(String args[]) {
        Box b = new Box(5, 10, 2);
        System.out.println("The volume of our box is: " + b.calculateVolume());

    }
}

class Box {
    private int length = 0;
    private int height = 0;
    private int width = 0;

    //constructor
    Box(int lengthParam, int heightParam, int widthParam) {
        length = lengthParam;
        height = heightParam;
        width = widthParam;
    }   
    
    int calculateVolume() {
        return (length * height * width);
    } 
}

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


C:\Java\ConstructorTwo>javac ConstructorTwo.java
C:\Java\ConstructorTwo>java ConstructorTwo
The volume of our box is: 100


Final thoughts

If you have been keeping up with previous tutorials, you should recall that we can set and get instance variables using setter and getter methods. By adding parameters to the constructor, we can assign values to the instance variables as the object is created.


Tutorials