Java – what’s the difference between creating objects in these two ways?

I want to know the difference between these:

1-)

JFrame frame = new JFrame();
JLabel label = new JLabel("example");
frame.add(label);

2-)

JFrame frame = new JFrame();
frame.add(new Label("example"));

In addition, we can use the following syntax:

1-)

new Timer(10,new ActionListener() {...}).start();

But why can't we use it like this:

2-)

Timer timer = new Timer(10,new ActionListener() {...}).start(); // we cannot use it this way it has to be like:

//Timer timer = new Timer(10,new ActionListener() {...});
//timer.start();

Solution

The difference between the two is this,

If you do not need to reference variables when sending parameter variables to methods as parameters, you can directly generate objects when calling methods

I like this frame add(new Label(“example”));

But if you do ask for an object that you will pass as a parameter, it's best to have its reference variable so that you can use it to do something in your code,

Suppose you want to change an instance variable or get the object state after the method completes its task In this case, you need to reference variables to object

Ramanlfc gives your answer to another question

It says the new timer (10, new actionlistener() {...}) start();

This can ignore the method return type here. This task will be completed when the statement is published,

but

Timer timer = new Timer(10,new ActionListener() {...}).start();

This is not possible because start () does not return the timer assigned to the timer reference variable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>