java – 以这两种方式创建对象有什么区别?
发布时间:2020-12-15 04:31:38 所属栏目:Java 来源:网络整理
导读:我想知道这些之间的区别是什么: 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 ActionL
我想知道这些之间的区别是什么:
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给出了你的另一个问题的回答 其中说新的Timer(10,new ActionListener(){…}).start(); 这可以在这里忽略方法返回类型,这个任务将在语句发布时完成, 但 Timer timer = new Timer(10,new ActionListener() {...}).start(); 这是不可能的,因为start()不会返回分配给Timer引用变量的Timer (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |