|
Your time now: Mon Nov 23, 2009 3:29 pm
|
View unanswered posts | View active topics
| Author |
Message |
|
Jose S
|
Post subject: short question for new learner Posted: Tue May 08, 2007 7:08 pm |
|
Joined: Tue May 08, 2007 6:50 pm Posts: 4
|
|
Hi, I am a new learner and have a question on creating objects of classes. Let start. Normally I always create an object of a class like the following code:
Car myCar = Car();
But I don't understand in some programs I saw which is similar to the following code.
List<String> contents = new ArrayList<String>();
What is the reason that we don't create like...ArrayList<String> contents = new ArrayList<String>(); could anyone pls clearify me?
|
|
| Top |
|
 |
|
meongmania
|
Post subject: Posted: Wed May 09, 2007 6:52 am |
|
Joined: Tue Dec 19, 2006 3:58 am Posts: 16
|
|
the
List contents = new ArrayList();
means that you r trying to create a new instance of ArrayList and defining the type of the object as List type. It also means that the class ArrayList inherits the List class. You can do that to other type of classes that inherits the List class suchas
- ArrayList
- LinkedList
it's actually an implementation of polymorphism...
|
|
| Top |
|
 |
|
skoiloth
|
Post subject: Posted: Wed May 09, 2007 12:03 pm |
|
Joined: Wed May 09, 2007 10:51 am Posts: 6
|
|
It's called "programming to an interface"
If you write "HashSet x = new HashSet();",
and your functions all take "HashSet" as arguments... then you have 2 problems:
1) What if later you decide that it is more efficient to use a different set (eg. TreeSet)?
You would have to rename your code all over the place.
2) What if you accidentally begin to rely on HashSet-specific methods?
(that is, methods that only HashSet has, but no other Set has).
Then later, if you want to change to something like TreeSet which doesn't have that method,
then you may have to do major rewrite of your code
such that it can work without that specific function!
Another way to put it is: chances are your code only cares that it is a Set.
Chances are your code doesn't care that it is a "HashSet".
So... it is logically preferred to reduce your dependency as much as possible.
_________________
|
|
| Top |
|
 |
|
Jose S
|
Post subject: Posted: Wed May 09, 2007 2:42 pm |
|
Joined: Tue May 08, 2007 6:50 pm Posts: 4
|
|
Thank for both of you. I ve got much better idea now.
|
|
| Top |
|
 |
|
Page 1 of 1
|
[ 4 posts ] |
|
Who is online |
Users browsing this forum: No registered users and 0 guests |
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot post attachments in this forum
|

|
|