user151841 user151841 - 5 months ago 12
Java Question

Why do you name the class twice during instantiation with java?

I'm new to java, and this question struck me. 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 delcare a string, I only say
String
once:

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?

Answer

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.,

Comments