user151841 user151841 - 6 months ago 21
Java Question

Why do you name the class twice during instantiation in Java?

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

OddEven number = new OddEven();

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

String str = "abc";

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?

My thoughts are:

  1. There is something fundamental to the way Java operates at a low level that necessitates typing the name twice, or

  2. The creators freely choose to do it this way to keep some aspect of the syntax uniform -- declare the type first? Or was it to be more like its predecessors?


Because you can do this:

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>();

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