为什么在Java实例化期间为类命名两次? [英] Why do you name the class twice during instantiation in Java?

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

问题描述

实例化对象时,为什么要两次指定类?

When you instantiate an object, why do you specify the class twice?

OddEven number = new OddEven();

为什么不能只说 number = new OddEven(); ?当我声明一个字符串时,我只说一次 String :

Why can't you just say number = new OddEven();? When I declare a string, I only say String once:

String str = "abc";

实际上,我的问题不是为什么要这样做"-显然,您这样做是因为必须这样做-而是,为什么创建者选择使Java语法像这样工作?

Actually, my question is not "why do you do it this way" -- obviously, you do it because you have to -- but rather, why did the creators choose to make Java syntax work like this?

我的想法是:

  1. Java在较低级别上运行的方式有一些基本要求,需要两次输入名称,或者
  2. 创建者可以自由选择这样做,以保持语法的某些方面统一-首先声明类型吗?还是更像其前辈?

推荐答案

因为您可以这样做:

Superclass x = new Subclass();

引用的类型可以是所声明的实际对象的超类,因此您需要同时指定两者.例如,您可以执行以下操作:

The type of the reference can be a superclass of the actual object being declared, so you need to specify both. For example, you can do:

List<String> stringList = new ArrayList<String>();

您的程序与实现List的对象进行交互,而您并不关心实现.

Your program interacts with objects that implement List, and you don't care about the implementation.,

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

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