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();
> 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.
> 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?
> 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.