我想知道它们之间有什么区别:
1-)
JFrame frame = new JFrame();
JLabel label = new JLabel("example");
frame.add(label);
2-)
JFrame frame = new JFrame();
frame.add(new Label("example"));
另外,我们可以使用这样的语法:
1-)
new Timer(10, new ActionListener() {...}).start();
但为什么我们不能这样使用它:
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();
最佳答案
这两者的区别是这样的,
如果在将引用变量作为参数发送给方法时不需要对象的引用变量,则可以在调用方法时直接生成对象。
像这样 frame.add(new Label("example"));
但是如果你确实需要你将作为参数传递的对象,最好是拥有它的引用变量,这样你就可以在后面的代码中对它做一些事情,
假设您想在方法完成其任务后更改一些实例变量或获取 Object
的状态。在这种情况下,您需要 Object
是的,Ramanlfc
给出了您其他问题的答案上面写着 new Timer(10, new ActionListener() {...}).start();
这可以完成,因为这里忽略了方法返回类型,这个任务将在发出的语句中完成,
但是
Timer timer = new Timer(10, new ActionListener() {...}).start();
这是不可能的,因为 start()
不会返回分配给 Timer
引用变量的 Timer
关于java - 用这两种方式创建对象有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34535600/