user151841 user151841 - 1 year ago 63
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 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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download