Java - 如何“name = new something(); "工作? [英] Java - how does "something name = new something(); " work?

查看:76
本文介绍了Java - 如何“name = new something(); "工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有真正理解这行代码如何工作,即使我自己多次使用它。我总是认为Something必须是特定的东西,比如图书馆中的某个组件或其他东西。例如,我认为它只能是 JButton buttonName = new JButton ();或类似的东西。但最近我发现它几乎可以是任何东西,比如Banana name = new Banana();。



我环顾了论坛,甚至在oracle网站上,但我无法确定这行代码是什么,所以我无法知道它是如何工作的。



可以有人请提供一个链接,无论是解释,还是带有答案的类似问题?



我尝试了什么:



试着在这个和其他网站上寻找答案。

I've never actually understood how this line of code works, even though I used it many times myself. I was always under the impression that the "Something" had to be something specific, like a component in a library or something. For example, I thought that it could only be "JButton buttonName = new JButton();" or something similar. But recently I found out that it can be pretty much anything, like "Banana name = new Banana();".

I've looked around the forums, and even on the oracle website, but I couldn't pin-point what this line of code is called, so I couldn't find out how it works.

Could someone please provide a link, either to an explanation, or to a similar question with an answer?

What I have tried:

Tried looking around this and other websites for answers.

推荐答案

参见 Lesson:类和对象(Java™教程>学习Java语言) [ ^ ]。


In c样式面向对象的语言,如java,如果你有(我把元素放在它自己的li中为清楚起见,注释中的参考编号):

In c style object orientated languages like java, if you have (I put the elements in it's own line for clarity with the reference number in comments):
JButton // 1
buttonName // 2
= // 3
new // 4
JButton(); // 5





3)你的=符号之前的任何东西是左侧或变量定义侧,后面的所有东西都是右侧或价值侧。



1)是变量的类型,因此编译器知道为内存分配的内容。

2)是您使用的变量的名称,因此您可以访问该对象。



5)是你正在创建的类型是一个对象

4)是一个关键字告诉编译器下一步是你想要的对象创建。



现在你可以在右侧创建任何具有可访问构造函数的对象(JButton,JLabel等...)如果不是你将得到错误。



3) any thing before your = sign is the left hand side or your variable definition side , and everything after is the right hand side or the value side.

1) is the type of the variable so the compiler knows what to allocate memory for.
2) is the name of the variable for your use so you can access the object.

5) is the type you are creating which is an object
4) is the keyword that tells the compiler that what comes next is the object you want to create.

Now you can create any object on the right hand side which has an accessible constructor to you (JButton, JLabel etc...) if not you will get an error.


这篇关于Java - 如何“name = new something(); "工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆