为什么在Java中实例化新对象时必须两次键入类名称? [英] Why do we have to type the class name twice when instantiating a new object in Java?

查看:55
本文介绍了为什么在Java中实例化新对象时必须两次键入类名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中创建新对象时,我们使用以下语法:

When we create a new object in Java, we use the syntax:

ClassName instancename = new ClassName();

我的问题是为什么我们必须在开头输入类名?为什么根本没有'object'关键字?

My question is why do we have to type the class name at the beginning? Why is there simply not an 'object' keyword?

示例:

object instancename = new ClassName();

推荐答案

在左侧:

ClassName instancename

ClassName 声明变量 instancename 的类型(=类).

The ClassName is declaring type (= class) of variable instancename.

在右侧:

new ClassName();

ClassName()正在调用名为 ClassName()的(构造函数)方法.

The ClassName() is invoking a (constructor) method named ClassName().

所以,您一次要做两件事.

So, you are doing two things at once.

ClassName instancename;         // declaring type
instancename = new ClassName(); // invoking method

您的示例:

ClassName instancename = new ClassName();

只是两个指令的简化形式.

is just shortened style of the two instructions.

还有其他获取类实例的样式,例如 newInstance() getInstance().

There are other styles of getting an instance of a class -- newInstance() or getInstance() for example.

也就是说,类型的声明和实例化的方法是分开的.出于自身目的需要它们.

That is: declaration of type and method of instantiation are the separate things. They are needed for their own purposes.

这篇关于为什么在Java中实例化新对象时必须两次键入类名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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