31

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?

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?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 4
    Even *if* the existence of `new` could have been avoided (and I didn't check if it could), why *should it*? It serves a purpose: it makes the allocation of (possibly large) objects explicit. – Joachim Sauer Jun 14 '11 at 07:51
  • 2
    @Stuti: the voting feature is not meant to rate your personal level of understanding ;) – Oben Sonne Jun 14 '11 at 07:52
  • @Stuti I have tried to clarify the question. I am not sure it is any clearer than before though! – juanchopanza Jun 14 '11 at 07:55
  • @Joachim Sauer but if using new is the only way to allocate these objects, then there isn't any real need to state it explicitly, right? – juanchopanza Jun 14 '11 at 07:57
  • @juanchopanza: depends on how you define "real need". If the only real needs are "technical requirements to make a compilable language", then yes: it's unnecessary. Just as method names, sane namespacing functionality and syntactic sugar for string concatenation are. And still: all of those exist and we're better of for it. Remember: the compiler is **not** the *only* consumer of your source code. – Joachim Sauer Jun 14 '11 at 07:59
  • @Joachim Sauer I guess if using or not using new in an expression was allowed and made a difference, I'd say there's a "real need" for the keyword. To me it looks a bit like an implementation detail, but that's probably my c++ background. – juanchopanza Jun 14 '11 at 08:04
  • @juanchopanza, The `new` keyword adds clarity. It can be avoided and youc an add factory methods to your classes to make it redundant if you wish. ;) – Peter Lawrey Jun 14 '11 at 08:05
  • @juanchopanza. The question is now a lot clearer. – Kaj Jun 14 '11 at 08:08
  • OK, so in the presence of factory methods, and plain methods with the same signature as the constructor, I guess new can be seen as the only way to be sure you're calling the constructor? – juanchopanza Jun 14 '11 at 08:18
  • 1
    http://programmers.stackexchange.com/a/47717/101683 – Elazar Dec 22 '14 at 21:28

5 Answers5

51

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.

artbristol
  • 32,010
  • 5
  • 70
  • 103
  • 6
    Never realized that kind of stunt were possible in Java. A whole new world of obfuscation by bad writing opens top me ! – Riduidel Jun 14 '11 at 07:53
  • In Eclipse the static method is italicized so it's not quite as bad but you're right, it's not good! – artbristol Jun 14 '11 at 07:54
  • 1
    Well, that code violates normal Java coding conventions, so that is not something that you would see in Java program. – Kaj Jun 14 '11 at 07:57
  • 1
    True, until a C# developer joins your project ;-) – artbristol Jun 14 '11 at 08:00
  • 7
    @Riduidel: to make it even more confusing: make the `TheClass` method a factory method that returns a new `TheClass` object, but make it act slightly different than the constructor. – Joachim Sauer Jun 14 '11 at 08:00
  • @artbristol: do you mean that such a construct is common/used in C#? Or do you expect them to accidentally write such methods? – Joachim Sauer Jun 14 '11 at 08:01
  • Method capitalization is usually UpperCamelCase in C# but lowerCamelCase in Java... I wouldn't expect them to accidentally write such methods! – artbristol Jun 14 '11 at 08:02
  • 4
    @Joachim so you could write `static TheClass TheClass()` OMFG ! Here be dragons ... – Riduidel Jun 14 '11 at 08:19
  • +1 it is all starting to make sense now. new indicates call to the constructor... – juanchopanza Jun 14 '11 at 08:48
  • 5
    It is highly improbable that Java designers laid out namespaces first, then were forced to add `new` keyword. It is very likely the opposite: `new` was there first, then they found that it allows them to have constructor names collide with other names. – irreputable Jun 14 '11 at 15:33
  • 2
    In short, the answer is "yes, but there's a conicidence, look:". – Elazar Dec 22 '14 at 21:15
14

Believe it or not, requiring the use of new for constructors is a namespacing thing. The following compiles just fine:

public class Foo {
    public Foo() {}
    public void Foo() {}
}
stevevls
  • 10,675
  • 1
  • 45
  • 50
  • 4
    It compiles just fine, but in my opinion it serves no purpose, except to confuse. The language would have been better off if it simply disallowed methods with the same name as the class/constructor. (I'd still leave the `new` keyword in, but that's a mostly independent discussion; also, I'm not the downvoter) – Joachim Sauer Jun 14 '11 at 07:50
  • @stevevls I'm not sure I follow. Do you have declarations of a method and a constructor here? Are you saying the constructor can be called from within the class without new? – juanchopanza Jun 14 '11 at 08:13
  • @juanchopanza Yes indeed, I have a constructor and a method. They have the same name and same type arguments, which is allowed because constructors and methods have different namespaces. That's why the `new` keyword is necessary. It instructs Java to look for a constructor and not a method. – stevevls Jun 14 '11 at 08:18
  • 1
    @stevevls, they dont like you; on a side note: the constructors in java are methods named . so the namespace part is very well put. – bestsss Jun 15 '11 at 08:34
6

I don't now why the java language designers decided to add the new statement to the java language, but, I don't want to miss it. Even if it could be redundant if it wasn't allowed to give classes, methods and fields the same name, like others have shown already in their answers:

Because - it greatly improves readability. Everytime I read that new statement, I realize immediately that a new object is born.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
-1

If you came from C++, why are you surprised? Doesn't C++ have the same new, for the same purpose? Java tries to follow most of C/C++ syntax, that's most likely the reason.

Commenting on artbristol's answer: It is highly improbable that Java designers laid out namespaces first, then were forced to add new keyword. It is very likely the opposite: new was there first, then they found that it allows them to have constructor names collide with other names.

irreputable
  • 44,725
  • 9
  • 65
  • 93
  • 9
    Because in C++ you don't have to use new to instantiate an object, whereas in Java you have to. – juanchopanza Jun 14 '11 at 15:33
  • 1
    Java has no "stack" objects, all objects are on heap. Java wanted to attract C++ programmers with the least confusion, so they better keep `new` for heap objects instantiation. – irreputable Jun 14 '11 at 15:36
  • I know about Java objects, but I think the real function of the new keyword has been pointed out by some of the answers here: because in Java you can have functions with the same name and signature as constructors, new disambiguates in these cases. A bit pathological, but so far it was the only example of when new is really necessary. – juanchopanza Jun 14 '11 at 15:39
  • 1
    That's confusing cause and effect. The mandatory use of `new` allowed constructor names be shared, not the other way around. – irreputable Jun 14 '11 at 15:51
  • I'm not saying anything about causality. I just wanted to know when new is not redundant. But it is interesting to know anyway. So they should've dropped new and disallowed sharing constructor names :-) – juanchopanza Jun 14 '11 at 15:53
  • we can program with 0 and 1, everything else is redundant. – irreputable Jun 14 '11 at 16:04
  • Clearly I am not suggesting that. I just wanted to find a good reason for new in Java. So far I haven't found one. The language could be as good as it is without it. – juanchopanza Jun 14 '11 at 16:16
  • @irreputable would you have a reference about the causality between the new keyword and the legality of functions with the same name as constructors? If so, it would be pretty interesting to see. It could also go in your answer, I'm sure others would find it useful. – juanchopanza Jun 15 '11 at 07:20
-3

The new must be written in Java to create a new object instance.

public class Foo {

    public void test() {
        final Foo foo1 = new Foo();
        final Foo foo2 = Foo();
    }

    public Foo Foo() {
        System.out.println("hello world");
        return this;
    }
}

Note, that methods starting with an uppercase character are discouraged in Java to avoid the confusion.

Mot
  • 28,248
  • 23
  • 84
  • 121
  • Yes, but my question is whether this is redundant in the language, i.e. whether the language would have been the same without this requirement. – juanchopanza Jun 14 '11 at 07:52
  • But pls note that I am not down-voting, my java skills are too low and I am still digesting all the answers. – juanchopanza Jun 14 '11 at 07:58
  • +1 OK it is starting to look like new is at least necessary to distinguish between method and constructor calls. – juanchopanza Jun 14 '11 at 08:47