Casting practice

Hi, If A implements B then:Is always good practice to utilize:B newObj = new A();and not A newObj = new A();My affirmation is correct?.is so.... why?Regards Fred
[231 byte] By [fredmobi28a] at [2007-11-27 9:42:23]
# 1

In general, yes, it's better to program to the interface. However, if you know that, because of how you're going to use newObj, what you require from it, etc., that it must be an A, and not just any old B (that is, if C implements B won't work here), then declare it as an A.

I generally declare List list = new ArrayList();

but if I know I'll need to randomly access elements of the list by index (get(i)), then I'd do ArrayList list = new ArrayList();

jverda at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 2
But what does this have to do with casting?
jverda at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 3
To echo jverd in rpely #2, this is casting:int num = (int) 12.34;
floundera at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 4
8-0 Thanks!
fredmobi28a at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 5

> To echo jverd in rpely #2, this is casting:

> > int num = (int) 12.34;

>

So is this:

B newObj = new A();

A a = (A)newObj; // This cast is necessary because...

a.someMethodThatADefinesButNotB(); // ... B doesn't have this method.

which is why you would declare newObj as type A if you know you're going to use it that way.

jverda at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 6

> I generally declare List list = new

> ArrayList();

but if I know I'll need to

> randomly access elements of the list by index

> (get(i)), then I'd do ArrayList list = new

> ArrayList();

Just curious, why is that since the List interface contains the get(int index) method declaration?

petes1234a at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 7

> Just curious, why is that since the List interface

> contains the get(int index) method declaration?

Because a List is ordered, so it makes sense to get the Nth element.

Certain implementations may not be efficient, but if you know you're going to be doing a lot of that, choose the appropriate implementation.

jverda at 2007-7-12 23:45:43 > top of Java-index,Java Essentials,Java Programming...
# 8
> Because a List is ordered, so it makes sense to get> the Nth element.> > Certain implementations may not be efficient, but if> you know you're going to be doing a lot of that,> choose the appropriate implementation.Thanks.
petes1234a at 2007-7-12 23:45:44 > top of Java-index,Java Essentials,Java Programming...