Constructors Part 3 Tutorial

In this tutorial I will be demonstrating how we can create an object and access its members without using a reference variable. You will see this technique used quite often.



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

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


class ConstructorThree {
    public static void main(String args[]) {
        System.out.println("The volume of our box is: " + new Box(5, 10, 2).calculateVolume());
        System.out.println("The volume of our box is: " + (new Box(5, 5, 5)).calculateVolume());
        System.out.println("The volume of our box is: " + (new Box(4, 8, 3)).calculateVolume());
	
        // Think really hard about this
        int boxVolumeA = new Box(5, 10, 2).calculateVolume();
        System.out.println(boxVolumeA);
	
        // The parenthesis should help
        int boxVolumeB = (new Box(5, 5, 5)).calculateVolume();
        System.out.println(boxVolumeB);
    }
}

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 ConstructorThree.java and press Enter.
Now type in java ConstructorThree and press Enter.


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


Final thoughts

Accessing objects members without a reference variable may seem quite confusing at first. It is something that you will see quite often and you need a clear understanding on what is going on. If this tutorial made zero sense, I would recommend a refresher on all of my OOP tutorials up to this point.


Tutorials