Anonymous object in Java

Leo De LeonLeo De Leon
2 min read

Watch the video on anonymous object below and jump right in to start coding session to try out how objects are created.

In Java, object is created using the new keyword. Object comes from a class. For instance, class A below would do.

class A {}

To debug, add a print statement System.out.println("object A created!"); inside a no-argument constructor public A(){}.

class A
{
    // no-arg constructor
    public A()
    {
        // print statement
        System.out.println("object A created!");
    }
}

Add a demo class class Demo {} with the main() method. In the main() method, create the anonymous object of class A.

class Demo 
{
    // main method
    public static void main(String[] args)
    {
        // creating an anonymous object of class A
        new A(); 
    }
}

Run Demo and observe the output

object A is created!

That's a clear sign that the no-arg constructor is invoked and therefore an object is created. That object, however, exist only in the heap memory with no way to reference back to that same object.

Next, add show() method in class A.

class A
{
    public A()
    {
        System.out.println("object A created!");
    }

    // add show() method
    public void show() 
    {
        System.out.println("in show");
    }
}

Call show() method in main. Create the object first, then invoke show method using dot notation.

class Demo 
{
    public static void main(String[] args)
    {
        // call show with dot notation
        new A().show(); 
    }
}

This time the output is

object A created!
in show

Now the object has a method, show(), which is also stored in the heap memory

0
Subscribe to my newsletter

Read articles from Leo De Leon directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Leo De Leon
Leo De Leon