• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about object & collection declaration

 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
My favorite is a chocolate cupcake with white frosting and tiny ad sprinkles.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic