Question

This is the code:

public class Main {
   public static void main(String[] args) {
        new Picture().edit();
    }
}

Why are there brackets infront of Picture?

There is a Picture class, which has an edit method, but the picture class also has a Picture method.

What is going on here?

Is the Picture class being created, which calls its picture method, while also calling the edit method aswell?

Thanks

Was it helpful?

Solution 2

new Picture() is instantiating a new picture object, which will call it's constructor. It's .edit(); is a method which it calls right away.

Since edit() is not static, it needs to be run from an instantiated class.

It's the same as typing

Picture pic = new Picture();
pic.edit();

The only difference is pic can be reused later without having to instantiate and construct a new Picture object every time.

Calling it by new Picture().edit(); is good for a short-handed way of doing a one off call on something as garbage collection will take care once it's finished executing.

OTHER TIPS

All you're doing here is creating a Picture instance via an argument-less (perhaps default) constructor. Subsequently, you call the edit() method on the instance you just created. Since you're not storing the Picture instance anywhere, it is eligible for garbage collection directly after the method call is complete.

For all practical purposes, you could have written your code as

Picture picture = new Picture();

picture.edit();

Note that a Picture method is not involved anywhere in your snippet. There is a difference between constructors and methods.


Why are there brackets infront of Picture?

This is simply the syntax of object creation in Java. It's clear that if the Picture constructor took some argument, then we would definitely need those brackets:

new Picture(someArg)

But the fact that we even need the brackets with a 0-arg constructor is purely a language design decision. I believe in a language like Scala (which also runs on the JVM) you can get away without using the brackets.

You are calling Picture class constructor and then edit() function. If there is a function named as Picture its never called. You may call it if want to.

Picture pic = new Picture();
pic.edit(); // call edit function

Picture pic = new Picture();
pic.Picture(); // call picture function

This is the constructor, it creates a new Picture object. If there were any arguments to the constructor, they would go inside the parenthesis.

new Picture()

Here we call the edit method on the newly created picture object:

new Picture().edit();

Since the Picture object is not saved it is lost afterwards. If you only want to make this one method call, it is probably ok.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top