Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

syntax

types

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 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?
like image 602
user151841 Avatar asked Dec 24 '09 03:12

user151841


1 Answers

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

like image 125
Jim Garrison Avatar answered Nov 12 '22 21:11

Jim Garrison