java中的`new`关键字是多余的吗? [英] Is the `new` keyword in java redundant?

查看:102
本文介绍了java中的`new`关键字是多余的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C ++,所以有一个我不太了解的java功能。我已经读过必须使用关键字 new 创建所有对象,但原语除外。现在,如果编译器可以识别基本类型,并且不允许您在没有 new 的情况下创建调用其构造函数的对象,那么关键字<$的原因是什么c $ c>新呢?有人提供一个例子,当两行代码相同,除了 new 的存在,编译并具有不同的含义/结果?

I am coming from C++ so there is one feature of java that I don't quite understand. I have read that all objects must be created using the keyword new, with the exception of primitives. Now, if the compiler can recognise a primitive type, and doesn't allow you to create an object calling its constructor without new, what is the reason to have the keyword new at all? Could someone provide an example when two lines of code, identical except for the presence of new, compile and have different meaning/results?

只是为了澄清多余的含义,希望能让我的问题更加清晰。 添加任何内容吗?是否可以在没有 new 的情况下表达语言,以便通过构造函数实例化对象?

Just to clarify what I mean by redundant, and hopefully make my question clearer. Does new add anything? Could the language have been expressed without new for instantiation of objects via a constructor?

推荐答案

方法和构造函数可以具有相同的名称。

Methods and constructors can have the same name.

public class NewTest {

    public static void main(final String[] args) {
        TheClass();
        new TheClass();
    }

    static void TheClass() {
        System.out.println("Method");
    }

    static class TheClass {
        TheClass() {
            System.out.println("Constructor");
        }
    }
}

这种语言设计选择是否是一个好主意是有争议的,但这就是它的工作方式。

Whether this language design choice was a good idea is debatable, but that's the way it works.

这篇关于java中的`new`关键字是多余的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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