• Post Reply Bookmark Topic Watch Topic
  • New Topic

about object & collection declaration  RSS feed

 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When i declare an object is usual to use the name of the object:
Box a = new Box();
but it is legal to use the Object class to do this work as:
Object a = new Box();
Could someone explain why?

Again when i use a collection i saw that there are many way to write it as:
Collection a = new ArrayList();
List a = new ArrayList();
ArrayList a = new ArrayList();
Wich is the best to use?
Tnks
 
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can always cast an object to another object that is (directly or indirectly) above it in the object hierarchy. Since Object is the root of the hierarchy, every object can be cast to it. Of course, you lose the ability to use all the features that distinguish it from Object.

As to your second question, that depends on what you're doing with the list. It's good practice to use an interface rather than a concrete class, because that frees you to later simply use something other than ArrayList (e.g. LinkedList), if that is beneficial for some reason (e.g. performance). If you had used the concrete class, you'd need to change all the places where it's passed as parameter.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!